gpt4 book ai didi

go - 在 Golang 中终止以 os/exec 开始的进程

转载 作者:IT老高 更新时间:2023-10-28 12:58:19 24 4
gpt4 key购买 nike

有没有办法终止在 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:

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.
}

请参阅 Go docs 中的此示例


旧版

在 Go 1.7 之前,我们没有 context 包,这个答案是不同的。

在超时后使用 channel 和 goroutine 运行和终止 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")
}

要么进程结束并且通过 done 接收到它的错误(如果有的话),要么已经过了 3 秒并且程序在完成之前被杀死。

关于go - 在 Golang 中终止以 os/exec 开始的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com