如何解决调用具有超时的可执行文件
我正在尝试使用 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,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
而不是 error
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。