| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "sort" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | // lingeringProcesses names the commands still running with a working directory |
| 12 | // inside dir: background work a worker left when its turn ended. Workers' |
| 13 | // tools often start commands in a new session, so the worktree, not the |
| 14 | // process group, ties them to the run. This process, its ancestors (the |
| 15 | // pane's shell), and processes attached to another terminal (someone's |
| 16 | // interactive shell) are skipped. It reads /proc, so it finds nothing where |
| 17 | // /proc is absent (macOS). |
| 18 | func lingeringProcesses(dir string) []string { |
| 19 | root, err := filepath.EvalSymlinks(dir) |
| 20 | if err != nil { |
| 21 | return nil |
| 22 | } |
| 23 | entries, err := os.ReadDir("/proc") |
| 24 | if err != nil { |
| 25 | return nil |
| 26 | } |
| 27 | skip := map[int]bool{} |
| 28 | for pid := os.Getpid(); pid > 1 && !skip[pid]; { |
| 29 | skip[pid] = true |
| 30 | pid, _ = procStat(pid) |
| 31 | } |
| 32 | _, ownTTY := procStat(os.Getpid()) |
| 33 | |
| 34 | seen := map[string]bool{} |
| 35 | var names []string |
| 36 | for _, e := range entries { |
| 37 | pid, err := strconv.Atoi(e.Name()) |
| 38 | if err != nil || skip[pid] { |
| 39 | continue |
| 40 | } |
| 41 | cwd, err := os.Readlink(filepath.Join("/proc", e.Name(), "cwd")) |
| 42 | if err != nil || (cwd != root && !strings.HasPrefix(cwd, root+string(filepath.Separator))) { |
| 43 | continue |
| 44 | } |
| 45 | if _, tty := procStat(pid); tty != 0 && tty != ownTTY { |
| 46 | continue |
| 47 | } |
| 48 | comm, err := os.ReadFile(filepath.Join("/proc", e.Name(), "comm")) |
| 49 | name := strings.TrimSpace(string(comm)) |
| 50 | if err != nil || name == "" || seen[name] { |
| 51 | continue |
| 52 | } |
| 53 | seen[name] = true |
| 54 | names = append(names, name) |
| 55 | } |
| 56 | sort.Strings(names) |
| 57 | return names |
| 58 | } |
| 59 | |
| 60 | // procStat returns a process's parent PID and controlling terminal (0 for |
| 61 | // none) from /proc/<pid>/stat, or zeros when it can't be read. |
| 62 | func procStat(pid int) (ppid, tty int) { |
| 63 | data, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) |
| 64 | if err != nil { |
| 65 | return 0, 0 |
| 66 | } |
| 67 | // The command name may contain spaces and parentheses; fields resume |
| 68 | // after the last ')': state, ppid, pgrp, session, tty_nr, ... |
| 69 | s := string(data) |
| 70 | f := strings.Fields(s[strings.LastIndexByte(s, ')')+1:]) |
| 71 | if len(f) < 5 { |
| 72 | return 0, 0 |
| 73 | } |
| 74 | ppid, _ = strconv.Atoi(f[1]) |
| 75 | tty, _ = strconv.Atoi(f[4]) |
| 76 | return ppid, tty |
| 77 | } |