当上下文取消命令时,我试图返回特定的错误。经过调查,ProcessState了解到,如果exitCode中为-1,则该过程会终止信号https://golang.org/pkg/os/#ProcessState.ExitCode但也许我们有更优雅的方式?也许我可以把这个错误从取消功能?可能不够用exitCode来了解命令是否已取消?
var (
CmdParamsErr = errors.New("failed to get params for execution command")
ExecutionCanceled = errors.New("command canceled")
)
func execute(m My) error {
filePath, args, err := cmdParams(m)
err = nil
if err != nil {
log.Infof("cmdParams: err: %v\n, m: %v\n", err, m)
return CmdParamsErr
}
var out bytes.Buffer
var errStd bytes.Buffer
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, filePath, args...)
cmd.Stdout = &out
cmd.Stderr = &errStd
err = cmd.Run()
if err != nil {
if cmd.ProcessState.ExitCode() == -1 {
log.Warnf("execution was canceled by signal, err: %v\n", err)
err = ExecutionCanceled
return err
} else {
log.Errorf("run failed, err: %v, filePath: %v, args: %v\n", err, filePath, args)
return err
}
}
return err
}
exec.ExitError没有提供退出代码的任何原因(没有相关的struct字段,也没有Unwrap方法),因此您必须直接检查上下文:
if ctx.Err() != nil {
log.Println("canceled")
}