go - 我什么时候应该明确调用 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
}
解决方案
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
}()
推荐阅读
- typescript - 打字稿:制作适合对象文字值的类型
- html - 如何将轮播放置在页面底部?
- macos - 如何在没有管理员权限的情况下安装 iTerm2?
- rest - 服务层应该接受来自控制器的 DTO 或自定义请求对象吗?
- winapi - masm 将浮点数传递给函数
- jupyter - jupyter nbconvert 无法与最新版本的 pandoc 一起使用
- node.js - 如何使用分片管理器从 ShardClientUtil 访问 shardArgs?
- javascript - HTML/CSS/JavaScript:无法单击幻灯片指示器按钮
- angular - 从角度 7 到电子的 pdf 文件的无声创建
- python - Keras 实现中的 LSTM 架构?