git连接:https://github.com/natefinch/deputy
deputy是go包,相当于在os系统上的一个轻量的cmd命令
deputy包结构体
- Deputy 结构体里面包含错误类型
- Cancel :当调用cancel方法时,会调用os底层signal,报出os:process already finished
type Deputy struct {
// Cancel, when closed, will cause the command to close.
Cancel <-chan struct{}
// Errors describes how errors should be handled.
Errors ErrorHandling
// StdoutLog takes a function that will receive lines written to stdout from
// the command (with the newline elided).
StdoutLog func([]byte)
// StdoutLog takes a function that will receive lines written to stderr from
// the command (with the newline elided).
StderrLog func([]byte)
// contains filtered or unexported fields
}
deputy包错误处理
type ErrorHandling int
const (
// DefaultErrs represents the default handling of command errors - this
// simply returns the error from Cmd.Run()
DefaultErrs ErrorHandling = iota
// FromStderr tells Deputy to convert the stderr output of a command into
// the text of an error, if the command exits with an error.
FromStderr
// FromStdout tells Deputy to convert the stdout output of a command into
// the text of an error, if the command exits with an error.
FromStdout
)
deputy包Run cmd命令
func (d Deputy) Run(cmd *exec.Cmd) error {
if err := d.makePipes(cmd); err != nil {
return err
}
errsrc := &bytes.Buffer{}
if d.Errors == FromStderr {
cmd.Stderr = dualWriter(cmd.Stderr, errsrc)
}
if d.Errors == FromStdout {
cmd.Stdout = dualWriter(cmd.Stdout, errsrc)
}
err := d.run(cmd)
if d.Errors == DefaultErrs {
return err
}
if err != nil && errsrc.Len() > 0 {
return fmt.Errorf("%s: %s", err, bytes.TrimSpace(errsrc.Bytes()))
}
return err
}
deputy包导入
import "github.com/natefinch/deputy"
func Runcmd() {
cancel := make(chan struct{})
go func() {
<-time.After(time.Second * 10)
close(cancel)
}()
d := deputy.Deputy{
Errors: deputy.FromStderr,
StdoutLog: func(b []byte) { log.Print(string(b)) },
Cancel: cancel,
}
if err := d.Run(exec.Command("cmd")); err != nil {
log.Printf("run cmd err %v", err)
}
}
注意Runcmd里的协程,当执行时间超过10s时会触发cancel,cancel传到os的signal触发os:process already finished,这里给出的解决方案是将时间调大