1//go:build linux
2
3package mcp
4
5import (
6 "errors"
7 "os"
8 "strconv"
9 "strings"
10
11 "golang.org/x/sys/unix"
12)
13
14// waitLeaderExited blocks until pid (our direct child) has exited, leaving it
15// unreaped (a zombie) so its pid, and with it the process-group id, cannot be
16// reused. It reports false if the wait failed.
17func waitLeaderExited(pid int) bool {
18 var info unix.Siginfo
19 for {
20 err := unix.Waitid(unix.P_PID, pid, &info, unix.WEXITED|unix.WNOWAIT, nil)
21 if errors.Is(err, unix.EINTR) {
22 continue
23 }
24 return err == nil
25 }
26}
27
28// liveGroupMembers reports whether any non-zombie process is in process group
29// pgid, reading /proc. known is false when /proc or a member's stat cannot be
30// read. The scan is not atomic, so callers use it only as a hint.
31func liveGroupMembers(pgid int) (live, known bool) {
32 entries, err := os.ReadDir("/proc")
33 if err != nil {
34 return false, false
35 }
36 sawProc := false
37 for _, e := range entries {
38 if _, err := strconv.Atoi(e.Name()); err != nil {
39 continue
40 }
41 sawProc = true
42 raw, err := os.ReadFile("/proc/" + e.Name() + "/stat")
43 if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) {
44 continue // exited meanwhile
45 }
46 if err != nil {
47 return false, false
48 }
49 state, group, ok := parseProcStat(string(raw))
50 if !ok || group != pgid || state == 'Z' || state == 'X' {
51 continue
52 }
53 return true, true
54 }
55 return false, sawProc
56}
57
58// parseProcStat extracts the state and process-group fields of a
59// /proc/<pid>/stat line. The command name is parenthesised and may itself
60// contain spaces and parentheses, so fields are counted after the last ')'.
61func parseProcStat(stat string) (state byte, pgrp int, ok bool) {
62 i := strings.LastIndexByte(stat, ')')
63 if i < 0 {
64 return 0, 0, false
65 }
66 fields := strings.Fields(stat[i+1:]) // state ppid pgrp ...
67 if len(fields) < 3 || len(fields[0]) != 1 {
68 return 0, 0, false
69 }
70 pg, err := strconv.Atoi(fields[2])
71 if err != nil {
72 return 0, 0, false
73 }
74 return fields[0][0], pg, true
75}