1 回答

TA貢獻1851條經驗 獲得超3個贊
你需要cmd.Wait()
讓它完成。(在一般的 Unix 中,您需要等待(2) 以避免泄漏僵尸。)
"os/exec"
沒有這個的非阻塞變體(沒有等同于waitpid?(2) 的變體)但是你可以在 goroutine 中等待:
// Start the subprocess
cmd := exec.Command("sleep", "500")
err := cmd.Start()
if err != nil {
? ? ? ? log.Fatal(err)
}
// Wait for it to finish
done := make(chan struct{})
go (func () {
? ? ? ? cmd.Wait()
? ? ? ? close(done)
})()
// Set a timeout
timeout := time.NewTimer(5 * time.Second)
select {
case <-done:
? ? ? ? fmt.Println("process completed")
? ? ? ? if !timeout.Stop() {
? ? ? ? ? ? ? ? <-timeout.C
? ? ? ? }
case <-timeout.C:
? ? ? ? fmt.Println("deadline ran out, killing process")
? ? ? ? if err := cmd.Process.Kill(); err != nil {
? ? ? ? ? ? ? ? log.Fatal("failed to kill process: ", err)
? ? ? ? }
? ? ? ? <-done
}
只有意志的一個分支select會觸發,并且每個分支都會為另一個執行必要的清理工作。在超時情況下,進程被殺死后,Wait()應該立即返回,這應該向“完成”通道發出信號。
- 1 回答
- 0 關注
- 233 瀏覽
添加回答
舉報