-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathexec.go
More file actions
42 lines (37 loc) · 886 Bytes
/
exec.go
File metadata and controls
42 lines (37 loc) · 886 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package exec
import (
"bytes"
"errors"
"os"
"os/exec"
"time"
)
// TimeoutedExec executes a timeouted command.
// The program path is defined by the name arguments, args are passed as arguments to the program.
//
// TimeoutedExec returns process output as a string (stdout) , and stderr as an error.
func TimeoutedExec(timeout time.Duration, name string, args ...string) (string, error) {
c := exec.Command(name, args...)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
c.Stdout = stdout
c.Stderr = stderr
if err := c.Start(); err != nil {
return "", err
}
done := make(chan error, 1)
go func() {
_, err := c.Process.Wait()
done <- err
}()
select {
case <-time.After(timeout):
c.Process.Signal(os.Kill)
case <-done:
}
res := string(stdout.Bytes())
if err := string(stderr.Bytes()); len(err) > 0 {
return res, errors.New(err)
}
return res, nil
}