-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgexec_linux.go
More file actions
95 lines (80 loc) · 1.66 KB
/
gexec_linux.go
File metadata and controls
95 lines (80 loc) · 1.66 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//go:build linux
// +build linux
package gexec
import (
"errors"
"os"
"strconv"
"syscall"
"golang.org/x/sys/unix"
)
func (c *GroupedCmd) start() error {
if c.Cmd.SysProcAttr != nil {
c.Cmd.SysProcAttr.Setpgid = true
} else {
c.Cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
if err := c.Cmd.Start(); err != nil {
return err
}
c.pgid = c.Cmd.Process.Pid
return nil
}
func checkValidPgid(pgid int) error {
if pgid == -1 {
return errors.New("invalid process group id")
}
if pgid == 0 {
return errors.New("process group id not assigned")
}
return nil
}
func (c *GroupedCmd) signalAll(sig os.Signal) error {
if err := checkValidPgid(c.pgid); err != nil {
return err
}
s, ok := sig.(syscall.Signal)
if !ok {
return errors.New("unsupported signal type")
}
return syscall.Kill(-c.pgid, s)
}
func (c *GroupedCmd) processes() ([]*Process, error) {
if err := checkValidPgid(c.pgid); err != nil {
return nil, err
}
pids, err := readPidsFromProc()
if err != nil {
return nil, err
}
var processes []*Process
for _, pid := range pids {
findPgid, err := unix.Getpgid(pid)
if err == nil && findPgid == c.pgid {
p, _ := os.FindProcess(pid)
processes = append(processes, &Process{Process: p})
}
}
return processes, nil
}
func readPidsFromProc() ([]int, error) {
var ret []int
d, err := os.Open("/proc")
if err != nil {
return nil, err
}
defer d.Close()
fnames, err := d.Readdirnames(-1)
if err != nil {
return nil, err
}
for _, fname := range fnames {
pid, err := strconv.ParseInt(fname, 10, 32)
if err != nil {
// if not numeric name, just skip
continue
}
ret = append(ret, int(pid))
}
return ret, nil
}