process_darwin.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. //go:build darwin
  2. // +build darwin
  3. package process
  4. import (
  5. "context"
  6. "fmt"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "github.com/shirou/gopsutil/v3/internal/common"
  11. "github.com/shirou/gopsutil/v3/net"
  12. "github.com/tklauser/go-sysconf"
  13. "golang.org/x/sys/unix"
  14. )
  15. // copied from sys/sysctl.h
  16. const (
  17. CTLKern = 1 // "high kernel": proc, limits
  18. KernProc = 14 // struct: process entries
  19. KernProcPID = 1 // by process id
  20. KernProcProc = 8 // only return procs
  21. KernProcAll = 0 // everything
  22. KernProcPathname = 12 // path to executable
  23. )
  24. var clockTicks = 100 // default value
  25. func init() {
  26. clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK)
  27. // ignore errors
  28. if err == nil {
  29. clockTicks = int(clkTck)
  30. }
  31. }
  32. type _Ctype_struct___0 struct {
  33. Pad uint64
  34. }
  35. func pidsWithContext(ctx context.Context) ([]int32, error) {
  36. var ret []int32
  37. kprocs, err := unix.SysctlKinfoProcSlice("kern.proc.all")
  38. if err != nil {
  39. return ret, err
  40. }
  41. for _, proc := range kprocs {
  42. ret = append(ret, int32(proc.Proc.P_pid))
  43. }
  44. return ret, nil
  45. }
  46. func (p *Process) PpidWithContext(ctx context.Context) (int32, error) {
  47. k, err := p.getKProc()
  48. if err != nil {
  49. return 0, err
  50. }
  51. return k.Eproc.Ppid, nil
  52. }
  53. func (p *Process) NameWithContext(ctx context.Context) (string, error) {
  54. k, err := p.getKProc()
  55. if err != nil {
  56. return "", err
  57. }
  58. name := common.ByteToString(k.Proc.P_comm[:])
  59. if len(name) >= 15 {
  60. cmdName, err := p.cmdNameWithContext(ctx)
  61. if err != nil {
  62. return "", err
  63. }
  64. if len(cmdName) > 0 {
  65. extendedName := filepath.Base(cmdName)
  66. if strings.HasPrefix(extendedName, p.name) {
  67. name = extendedName
  68. } else {
  69. name = cmdName
  70. }
  71. }
  72. }
  73. return name, nil
  74. }
  75. func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) {
  76. k, err := p.getKProc()
  77. if err != nil {
  78. return 0, err
  79. }
  80. return k.Proc.P_starttime.Sec*1000 + int64(k.Proc.P_starttime.Usec)/1000, nil
  81. }
  82. func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) {
  83. r, err := callPsWithContext(ctx, "state", p.Pid, false, false)
  84. if err != nil {
  85. return []string{""}, err
  86. }
  87. status := convertStatusChar(r[0][0][0:1])
  88. return []string{status}, err
  89. }
  90. func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) {
  91. // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details
  92. pid := p.Pid
  93. out, err := invoke.CommandWithContext(ctx, "ps", "-o", "stat=", "-p", strconv.Itoa(int(pid)))
  94. if err != nil {
  95. return false, err
  96. }
  97. return strings.IndexByte(string(out), '+') != -1, nil
  98. }
  99. func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) {
  100. k, err := p.getKProc()
  101. if err != nil {
  102. return nil, err
  103. }
  104. // See: http://unix.superglobalmegacorp.com/Net2/newsrc/sys/ucred.h.html
  105. userEffectiveUID := int32(k.Eproc.Ucred.Uid)
  106. return []int32{userEffectiveUID}, nil
  107. }
  108. func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) {
  109. k, err := p.getKProc()
  110. if err != nil {
  111. return nil, err
  112. }
  113. gids := make([]int32, 0, 3)
  114. gids = append(gids, int32(k.Eproc.Pcred.P_rgid), int32(k.Eproc.Pcred.P_rgid), int32(k.Eproc.Pcred.P_svgid))
  115. return gids, nil
  116. }
  117. func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) {
  118. return nil, common.ErrNotImplementedError
  119. // k, err := p.getKProc()
  120. // if err != nil {
  121. // return nil, err
  122. // }
  123. // groups := make([]int32, k.Eproc.Ucred.Ngroups)
  124. // for i := int16(0); i < k.Eproc.Ucred.Ngroups; i++ {
  125. // groups[i] = int32(k.Eproc.Ucred.Groups[i])
  126. // }
  127. // return groups, nil
  128. }
  129. func (p *Process) TerminalWithContext(ctx context.Context) (string, error) {
  130. return "", common.ErrNotImplementedError
  131. /*
  132. k, err := p.getKProc()
  133. if err != nil {
  134. return "", err
  135. }
  136. ttyNr := uint64(k.Eproc.Tdev)
  137. termmap, err := getTerminalMap()
  138. if err != nil {
  139. return "", err
  140. }
  141. return termmap[ttyNr], nil
  142. */
  143. }
  144. func (p *Process) NiceWithContext(ctx context.Context) (int32, error) {
  145. k, err := p.getKProc()
  146. if err != nil {
  147. return 0, err
  148. }
  149. return int32(k.Proc.P_nice), nil
  150. }
  151. func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) {
  152. return nil, common.ErrNotImplementedError
  153. }
  154. func convertCPUTimes(s string) (ret float64, err error) {
  155. var t int
  156. var _tmp string
  157. if strings.Contains(s, ":") {
  158. _t := strings.Split(s, ":")
  159. switch len(_t) {
  160. case 3:
  161. hour, err := strconv.Atoi(_t[0])
  162. if err != nil {
  163. return ret, err
  164. }
  165. t += hour * 60 * 60 * clockTicks
  166. mins, err := strconv.Atoi(_t[1])
  167. if err != nil {
  168. return ret, err
  169. }
  170. t += mins * 60 * clockTicks
  171. _tmp = _t[2]
  172. case 2:
  173. mins, err := strconv.Atoi(_t[0])
  174. if err != nil {
  175. return ret, err
  176. }
  177. t += mins * 60 * clockTicks
  178. _tmp = _t[1]
  179. case 1, 0:
  180. _tmp = s
  181. default:
  182. return ret, fmt.Errorf("wrong cpu time string")
  183. }
  184. } else {
  185. _tmp = s
  186. }
  187. _t := strings.Split(_tmp, ".")
  188. if err != nil {
  189. return ret, err
  190. }
  191. h, err := strconv.Atoi(_t[0])
  192. t += h * clockTicks
  193. h, err = strconv.Atoi(_t[1])
  194. t += h
  195. return float64(t) / float64(clockTicks), nil
  196. }
  197. func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) {
  198. pids, err := common.CallPgrepWithContext(ctx, invoke, p.Pid)
  199. if err != nil {
  200. return nil, err
  201. }
  202. ret := make([]*Process, 0, len(pids))
  203. for _, pid := range pids {
  204. np, err := NewProcessWithContext(ctx, pid)
  205. if err != nil {
  206. return nil, err
  207. }
  208. ret = append(ret, np)
  209. }
  210. return ret, nil
  211. }
  212. func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) {
  213. return net.ConnectionsPidWithContext(ctx, "all", p.Pid)
  214. }
  215. func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) {
  216. return net.ConnectionsPidMaxWithContext(ctx, "all", p.Pid, max)
  217. }
  218. func ProcessesWithContext(ctx context.Context) ([]*Process, error) {
  219. out := []*Process{}
  220. pids, err := PidsWithContext(ctx)
  221. if err != nil {
  222. return out, err
  223. }
  224. for _, pid := range pids {
  225. p, err := NewProcessWithContext(ctx, pid)
  226. if err != nil {
  227. continue
  228. }
  229. out = append(out, p)
  230. }
  231. return out, nil
  232. }
  233. // Returns a proc as defined here:
  234. // http://unix.superglobalmegacorp.com/Net2/newsrc/sys/kinfo_proc.h.html
  235. func (p *Process) getKProc() (*unix.KinfoProc, error) {
  236. return unix.SysctlKinfoProc("kern.proc.pid", int(p.Pid))
  237. }
  238. // call ps command.
  239. // Return value deletes Header line(you must not input wrong arg).
  240. // And splited by Space. Caller have responsibility to manage.
  241. // If passed arg pid is 0, get information from all process.
  242. func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) {
  243. var cmd []string
  244. if pid == 0 { // will get from all processes.
  245. cmd = []string{"-ax", "-o", arg}
  246. } else if threadOption {
  247. cmd = []string{"-x", "-o", arg, "-M", "-p", strconv.Itoa(int(pid))}
  248. } else {
  249. cmd = []string{"-x", "-o", arg, "-p", strconv.Itoa(int(pid))}
  250. }
  251. if nameOption {
  252. cmd = append(cmd, "-c")
  253. }
  254. out, err := invoke.CommandWithContext(ctx, "ps", cmd...)
  255. if err != nil {
  256. return [][]string{}, err
  257. }
  258. lines := strings.Split(string(out), "\n")
  259. var ret [][]string
  260. for _, l := range lines[1:] {
  261. var lr []string
  262. if nameOption {
  263. lr = append(lr, l)
  264. } else {
  265. for _, r := range strings.Split(l, " ") {
  266. if r == "" {
  267. continue
  268. }
  269. lr = append(lr, strings.TrimSpace(r))
  270. }
  271. }
  272. if len(lr) != 0 {
  273. ret = append(ret, lr)
  274. }
  275. }
  276. return ret, nil
  277. }