我什么时候应该显式调用cmd.Process.Release()?

时间:2019-07-04 13:30:14

标签: go

我不知道命令何时返回结果,并且设置了默认计时器。然后我有这个问题。

sigChan := make(os.Signal, 1)
signal.Notify(sigChan, SIGCHLD)
cmd := exec.Command(...)
cmd.Start()
select {
    case <-time.After(1e9):
    // kill the process and release?
    case <-sigChan:
    // the process has been terminated
}

1 个答案:

答案 0 :(得分:0)

如果要在超时后终止命令,请使用exec.CommandContext()

然后,您需要等待命令返回以获取其结果。因此,请使用cmd.Run()而不是cmd.Start()。如果需要考虑阻塞,请生成一个goroutine来阻塞并等待命令终止。

例如:

go func() {
    ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
    defer cancel()
    cmd := exec.CommandContext(ctx, ...)
    err := cmd.Run()
    //Process error or results
}()