-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd.go
68 lines (56 loc) · 1.28 KB
/
cmd.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package rerun
import (
"fmt"
"os"
"os/exec"
"syscall"
)
type Cmd struct {
cmd *exec.Cmd
args []string
}
func StartCommand(args ...string) (*Cmd, error) {
c := &Cmd{
args: args,
}
if err := c.Start(); err != nil {
return nil, err
}
return c, nil
}
func (c *Cmd) Start() error {
cmd := exec.Command(c.args[0], c.args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
return err
}
c.cmd = cmd
return nil
}
func (c *Cmd) Kill() error {
// Try to kill the whole process group (which we created via Setpgid: true), if possible.
// This should kill the command process, all its children and grandchildren.
if pgid, err := syscall.Getpgid(c.cmd.Process.Pid); err == nil {
_ = syscall.Kill(-pgid, 9)
}
// Kill the process.
// Note: The process group kill syscall sometimes fails on Mac OS, so let's just do both.
return c.cmd.Process.Kill()
}
func (c *Cmd) Wait() error {
// Wait for the process to finish.
return c.cmd.Wait()
}
func (c *Cmd) PID() string {
return fmt.Sprintf("PID %v: %v", c.cmd.Process.Pid, c.cmd.ProcessState.String())
}
func (c *Cmd) String() string {
str := "$"
for _, arg := range c.args {
str += " " + arg
}
return str
}