如何解决在 Golang 中终止以 os/exec 启动的进程?

@H_301_0@运行并终止一个
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)
}
@H_301_0@
exec.Process
超时后运行并终止:
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
defer cancel()

if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
    // This will fail after 3 seconds. The 5 second sleep
    // will be interrupted.
}
@H_301_0@请参阅Go 文档中的此示例 @H_301_0@ @H_301_0@
context
@H_301_0@
exec.Process
使用通道和 goroutine 在超时后运行和终止:
// 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")
}
@H_301_0@要么进程结束并接收到它的错误(如果有),
done
要么已经过去了 3 秒并且程序在完成之前被终止。

解决方法