首页 > 解决方案 > 使用超时调用可执行文件

问题描述

我正在尝试使用该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()返回类型*Cmdnot error

标签: gocommandtimeout

解决方案


推荐阅读