go - 使用超时调用可执行文件
问题描述
我正在尝试使用该context
软件包以 10 秒的超时时间运行二进制文件,例如:
func RunQL(file db.File, flag string) string {
// 10-second timeout for the binary to run
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "qltool", "run", "-f", file.Path, "--rootfs", file.Root, "--args", flag)
out, err := cmd.Output()
// check to see if our timeout was executed
if ctx.Err() == context.DeadlineExceeded {
return ""
}
// no timeout (either completed successfully or errored)
if err != nil {
return ""
}
return string(out)
}
但是由于某种原因,如果该过程持续时间超过 10 秒,它仍然会挂起。不知道是什么原因造成的,我还注意到该CommandContext()
函数的文档似乎是错误的/具有误导性?它显示以下代码:
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
// This will fail after 100 milliseconds. The 5 second sleep
// will be interrupted.
}
}
但CommandContext()
返回类型*Cmd
not error
。
解决方案
推荐阅读
- javascript - 如何使用 jquery 在单击时添加引导表单组?
- javascript - 如何在一个 id 中制作多个 Popover?
- python - Tensorflow - scipy.linalg.circulant 的等价性
- go - golang地图不添加元素
- python - 如何将工作预览和设置面板添加到使用 auto-py-to-exe 制作的屏幕保护程序中?
- sql - 协助设计数据库关系?
- javascript - 在mongodb更改流中为同时插入的文档获取相同的恢复令牌
- haskell - Haskell Aeson 如何根据`Value` 类型而不是`ByteString` 解码/解析?
- python-3.x - 从 Python 脚本执行外部程序
- php - 登录后如何将用户引导到另一个站点?