12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package main
- import (
- "bytes"
- "fmt"
- "math/rand"
- "os/exec"
- "strings"
- "syscall"
- "time"
- )
- func AccountShuffle(list []Account) {
- rand.Seed(time.Now().UnixNano())
- rand.Shuffle(len(list), func(i, j int) {
- list[i], list[j] = list[j], list[i]
- })
- }
- func CheckError(err error) {
- if err != nil {
- panic(err)
- }
- }
- // 运行Shell命令,设定超时时间(秒)
- func ShellCmdTimeout(timeout int, cmd string, args ...string) (stdout, stderr string, e error) {
- if len(cmd) == 0 {
- e = fmt.Errorf("cannot run a empty command")
- return
- }
- var out, err bytes.Buffer
- command := exec.Command(cmd, args...)
- command.Stdout = &out
- command.Stderr = &err
- command.Start()
- // 启动routine等待结束
- done := make(chan error)
- go func() { done <- command.Wait() }()
- // 启动routine持续打印输出
- // 设定超时时间,并select它
- after := time.After(time.Duration(timeout) * time.Second)
- select {
- case <-after:
- command.Process.Signal(syscall.SIGINT)
- time.Sleep(time.Second)
- command.Process.Kill()
- case <-done:
- }
- stdout = trimOutput(out)
- stderr = trimOutput(err)
- return
- }
- func trimOutput(buffer bytes.Buffer) string {
- return strings.TrimSpace(string(bytes.TrimRight(buffer.Bytes(), "\x00")))
- }
|