You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.5 KiB

1 year ago
package command
import (
"bytes"
1 year ago
"errors"
"fmt"
"os/exec"
1 year ago
"strings"
"syscall"
"time"
)
// ExecCommand 执行cmd命令操作
func ExecCommand(name string, args []string, timeout ...time.Duration) (out string, err error) {
var (
stderr, stdout bytes.Buffer
expire = 30 * time.Minute
1 year ago
errs []string
)
if len(timeout) > 0 {
expire = timeout[0]
}
cmd := exec.Command(name, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
1 year ago
err = cmd.Start()
if err != nil {
err = fmt.Errorf("%s\n%s", err.Error(), stderr.String())
return
}
pid := 0
if cmd.Process != nil && cmd.Process.Pid != 0 {
pid = cmd.Process.Pid
pidMap.Store(pid, pid)
}
defer func() {
if pid != 0 {
pidMap.Delete(pid)
}
}()
1 year ago
time.AfterFunc(expire, func() {
if cmd.Process != nil && cmd.Process.Pid != 0 {
1 year ago
errs = append(errs, fmt.Sprintf("execute timeout: %d min.", int(expire.Minutes())))
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
cmd.Process.Kill()
}
1 year ago
})
err = cmd.Wait()
if err != nil {
errs = append(errs, err.Error(), stderr.String())
}
out = stdout.String()
1 year ago
if len(errs) > 0 {
errs = append(errs, out)
err = errors.New(strings.Join(errs, "\n\r"))
}
return
}
// 当主程序退出时从pidMap中获取所有的pid然后kill掉
func CloseChildProccess() {
pidMap.Range(func(key, value interface{}) bool {
if pid, ok := value.(int); ok {
fmt.Println("kill pid:", pid)
syscall.Kill(-pid, syscall.SIGKILL)
}
return true
})
}