调用具有超时的可执行文件

问题描述

我正在尝试使用 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 (将#修改为@)