gocron/modules/utils/utils_unix.go

38 lines
855 B
Go
Raw Normal View History

// +build !windows
package utils
import (
"os/exec"
"syscall"
2017-05-26 13:59:01 +00:00
"golang.org/x/net/context"
"errors"
)
2017-05-26 13:59:01 +00:00
type Result struct {
output string
err error
}
// 执行shell命令可设置执行超时时间
2017-05-26 13:59:01 +00:00
func ExecShell(ctx context.Context, command string) (string, error) {
2017-05-26 10:09:07 +00:00
cmd := exec.Command("/bin/bash", "-c", command)
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
2017-05-26 13:59:01 +00:00
var resultChan chan Result = make(chan Result)
go func() {
output ,err := cmd.CombinedOutput()
2017-05-26 13:59:01 +00:00
resultChan <- Result{string(output), err}
}()
select {
case <- ctx.Done():
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
return "", errors.New("timeout killed")
case result := <- resultChan:
return result.output, result.err
}
2017-05-26 13:59:01 +00:00
return "", nil
}