首页 > 解决方案 > 我什么时候应该明确调用 cmd.Process.Release() ?

问题描述

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

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
}

标签: go

解决方案


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
}()

推荐阅读