go执行cmd命令出现os:process already finished

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,这里给出的解决方案是将时间调大

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值