gocron/modules/utils/utils_unix.go

33 lines
735 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// +build !windows
package utils
import (
"os/exec"
"syscall"
"time"
)
// 执行shell命令可设置执行超时时间
func ExecShellWithTimeout(timeout int, command string) (string, error) {
cmd := exec.Command("/bin/bash", "-c", command)
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
}