forked from VojtechVitek/rerun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmddarwin.go
67 lines (53 loc) · 1.33 KB
/
cmddarwin.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
package rerun
import (
"fmt"
"os"
"os/exec"
"syscall"
)
type DarwinCmd struct {
*command
}
var _ Command = &DarwinCmd{}
func NewDarwinCmd(args ...string) *DarwinCmd {
return &DarwinCmd{command: &command{args: args}}
}
func (c *DarwinCmd) Start() error {
cmd := exec.Command("/bin/sh", append([]string{"-c"}, c.args...)...)
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 *DarwinCmd) Kill() error {
pid := c.cmd.Process.Pid
// 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(pid); err == nil {
_ = syscall.Kill(-pgid, syscall.SIGKILL)
}
// Kill the process.
// Note: The process group kill syscall sometimes fails on Mac OS, so let's just do both.
err := syscall.Kill(-pid, syscall.SIGKILL)
c.cmd.Process.Wait()
return err
}
func (c *DarwinCmd) Wait() error {
// Wait for the process to finish.
return c.cmd.Wait()
}
func (c *DarwinCmd) PID() string {
if c.cmd != nil {
return fmt.Sprintf("PID %v", c.cmd.Process.Pid)
} else {
return "PID unknown"
}
}
func (c *DarwinCmd) String() string {
return c.PID()
}