在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秒后)终止该过程?


蓝山帝景
浏览 261回答 3
3回答

开心每一天1111

终止运行exec.Process:// Start a process:cmd := exec.Command("sleep", "5")if err := cmd.Start(); err != nil {&nbsp; &nbsp; log.Fatal(err)}// Kill it:if err := cmd.Process.Kill(); err != nil {&nbsp; &nbsp; log.Fatal("failed to kill process: ", err)}exec.Process超时后终止运行:// Start a process:cmd := exec.Command("sleep", "5")if err := cmd.Start(); err != nil {&nbsp; &nbsp; 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() {&nbsp; &nbsp; done <- cmd.Wait()}()select {case <-time.After(3 * time.Second):&nbsp; &nbsp; if err := cmd.Process.Kill(); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("failed to kill process: ", err)&nbsp; &nbsp; }&nbsp; &nbsp; log.Println("process killed as timeout reached")case err := <-done:&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("process finished with error = %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; log.Print("process finished successfully")}该过程结束并且在done3秒钟内收到了错误(如果有的话),并且该程序在完成之前被终止了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go