2017-05-05 05:44:44 +00:00
|
|
|
|
// +build !windows
|
|
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"os/exec"
|
|
|
|
|
"syscall"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// 执行shell命令,可设置执行超时时间
|
2017-05-26 10:09:07 +00:00
|
|
|
|
func ExecShellWithTimeout(timeout int, command string) (string, error) {
|
|
|
|
|
cmd := exec.Command("/bin/bash", "-c", command)
|
2017-05-05 05:44:44 +00:00
|
|
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{
|
|
|
|
|
Setpgid: true,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 不限制超时
|
|
|
|
|
if timeout == 0 {
|
|
|
|
|
output ,err := cmd.CombinedOutput()
|
|
|
|
|
return string(output), err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
d := time.Duration(timeout) * time.Second
|
|
|
|
|
timer := time.AfterFunc(d, func() {
|
|
|
|
|
// 超时kill进程
|
|
|
|
|
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
|
|
|
|
})
|
|
|
|
|
output ,err := cmd.CombinedOutput()
|
|
|
|
|
timer.Stop()
|
|
|
|
|
|
|
|
|
|
return string(output), err
|
|
|
|
|
}
|