ExecDirEnv is the same as ExecDir but allows appending additional environment variables to the child process. Pass nil for env to inherit the parent process environment unchanged.
(timeout time.Duration, dir string, env []string, desc, cmdName string, args ...string)
| 79 | // variables to the child process. Pass nil for env to inherit the parent |
| 80 | // process environment unchanged. |
| 81 | func ExecDirEnv(timeout time.Duration, dir string, env []string, desc, cmdName string, args ...string) (string, string, error) { |
| 82 | if timeout == -1 { |
| 83 | timeout = defaultTimeout |
| 84 | } |
| 85 | |
| 86 | bufOut := new(bytes.Buffer) |
| 87 | bufErr := new(bytes.Buffer) |
| 88 | |
| 89 | cmd := exec.Command(cmdName, args...) |
| 90 | cmd.Dir = dir |
| 91 | cmd.Stdout = bufOut |
| 92 | cmd.Stderr = bufErr |
| 93 | if len(env) > 0 { |
| 94 | cmd.Env = append(os.Environ(), env...) |
| 95 | } |
| 96 | if err := cmd.Start(); err != nil { |
| 97 | return "", err.Error(), err |
| 98 | } |
| 99 | |
| 100 | pid := Add(desc, cmd) |
| 101 | done := make(chan error) |
| 102 | go func() { |
| 103 | done <- cmd.Wait() |
| 104 | }() |
| 105 | |
| 106 | var err error |
| 107 | select { |
| 108 | case <-time.After(timeout): |
| 109 | if errKill := Kill(pid); errKill != nil { |
| 110 | log.Error("Failed to kill timeout process [pid: %d, desc: %s]: %v", pid, desc, errKill) |
| 111 | } |
| 112 | <-done |
| 113 | return "", ErrExecTimeout.Error(), ErrExecTimeout |
| 114 | case err = <-done: |
| 115 | } |
| 116 | |
| 117 | Remove(pid) |
| 118 | return bufOut.String(), bufErr.String(), err |
| 119 | } |
| 120 | |
| 121 | // Exec starts executing a shell command, it tracks corresponding process and timeout. |
| 122 | func ExecTimeout(timeout time.Duration, desc, cmdName string, args ...string) (string, string, error) { |