( executor: CommandExecutor, startPid = process.pid.toString(), )
| 13 | }; |
| 14 | |
| 15 | export async function getProcessTree( |
| 16 | executor: CommandExecutor, |
| 17 | startPid = process.pid.toString(), |
| 18 | ): Promise<ProcessTreeResult> { |
| 19 | const results: ProcessTreeEntry[] = []; |
| 20 | const seen = new Set<string>(); |
| 21 | let currentPid = startPid; |
| 22 | let lastError: string | undefined; |
| 23 | |
| 24 | const parseLine = (line: string): ProcessTreeEntry | null => { |
| 25 | const tokens = line.trim().split(/\s+/); |
| 26 | if (tokens.length < 3) { |
| 27 | return null; |
| 28 | } |
| 29 | const pid = tokens[0]; |
| 30 | const ppid = tokens[1]; |
| 31 | const name = tokens[2]; |
| 32 | if (!pid || !ppid || !name) { |
| 33 | return null; |
| 34 | } |
| 35 | const command = tokens.slice(3).join(' '); |
| 36 | return { pid, ppid, name, command }; |
| 37 | }; |
| 38 | |
| 39 | const fetchProcessInfo = async (pid: string): Promise<ProcessTreeEntry | null> => { |
| 40 | const command = ['-o', 'pid=,ppid=,comm=,args=', '-p', pid]; |
| 41 | const attempts = [ |
| 42 | { bin: '/bin/ps', label: 'Get process info (ps)' }, |
| 43 | { bin: 'ps', label: 'Get process info (ps fallback)' }, |
| 44 | ]; |
| 45 | |
| 46 | for (const attempt of attempts) { |
| 47 | try { |
| 48 | const res = await executor([attempt.bin, ...command], attempt.label); |
| 49 | if (!res.success) { |
| 50 | lastError = res.error ?? `ps returned non-zero exit code for pid ${pid}`; |
| 51 | continue; |
| 52 | } |
| 53 | const line = res.output.trim().split('\n')[0]?.trim(); |
| 54 | if (!line) { |
| 55 | lastError = `ps returned no output for pid ${pid}`; |
| 56 | continue; |
| 57 | } |
| 58 | const parsed = parseLine(line); |
| 59 | if (!parsed) { |
| 60 | lastError = `ps output was not parseable for pid ${pid}`; |
| 61 | continue; |
| 62 | } |
| 63 | return parsed; |
| 64 | } catch (error) { |
| 65 | lastError = error instanceof Error ? error.message : String(error); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | return null; |
| 70 | }; |
| 71 | |
| 72 | while (currentPid && currentPid !== '0' && !seen.has(currentPid)) { |
no test coverage detected