在Golang中终止以os / exec开头的进程

有没有办法终止Golang中以os.exec开始的进程?例如(来自http://golang.org/pkg/os/exec/#example_Cmd_Start),

cmd := exec.Command("sleep", "5")

err := cmd.Start()

if err != nil {

log.Fatal(err)

}

log.Printf("Waiting for command to finish...")

err = cmd.Wait()

log.Printf("Command finished with error: %v", err)

是否可以提前3秒后终止该过程?

提前致谢

回答:

终止运行exec.Process

// Start a process:

cmd := exec.Command("sleep", "5")

if err := cmd.Start(); err != nil {

log.Fatal(err)

}

// Kill it:

if err := cmd.Process.Kill(); err != nil {

log.Fatal("failed to kill process: ", err)

}

exec.Process超时后终止运行:

// Start a process:

cmd := exec.Command("sleep", "5")

if err := cmd.Start(); err != nil {

log.Fatal(err)

}

// Wait for the process to finish or kill it after a timeout (whichever happens first):

done := make(chan error, 1)

go func() {

done <- cmd.Wait()

}()

select {

case <-time.After(3 * time.Second):

if err := cmd.Process.Kill(); err != nil {

log.Fatal("failed to kill process: ", err)

}

log.Println("process killed as timeout reached")

case err := <-done:

if err != nil {

log.Fatalf("process finished with error = %v", err)

}

log.Print("process finished successfully")

}

该过程结束并且在done3秒钟内收到了错误(如果有的话),并且该程序在完成之前被终止了。

以上是 在Golang中终止以os / exec开头的进程 的全部内容, 来源链接: utcz.com/qa/403193.html

回到顶部