有没有办法终止一个进程以os.exec开始在Golang?例如(从
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秒后?
提前致谢
启动命令后:
原文链接:https://www.f2er.com/go/187751.htmldone := 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: ",err) } log.Println("process killed as timeout reached") case err := <-done: if err != nil { log.Printf("process done with error = %v",err) } else { log.Print("process done gracefully without error") } }
或者:
>过程结束,并通过完成接收其错误(如果有)> 3秒过去了,程序被杀死。