genericProcessUtils.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import {
  2. execFileNoThrowWithCwd,
  3. execSyncWithDefaults_DEPRECATED,
  4. } from './execFileNoThrow.js'
  5. // This file contains platform-agnostic implementations of common `ps` type commands.
  6. // When adding new code to this file, make sure to handle:
  7. // - Win32, as `ps` within cygwin and WSL may not behave as expected, particularly when attempting to access processes on the host.
  8. // - Unix vs BSD-style `ps` have different options.
  9. /**
  10. * Check if a process with the given PID is running (signal 0 probe).
  11. *
  12. * PID ≤ 1 returns false (0 is current process group, 1 is init).
  13. *
  14. * Note: `process.kill(pid, 0)` throws EPERM when the process exists but is
  15. * owned by another user. This reports such processes as NOT running, which
  16. * is conservative for lock recovery (we won't steal a live lock).
  17. */
  18. export function isProcessRunning(pid: number): boolean {
  19. if (pid <= 1) return false
  20. try {
  21. process.kill(pid, 0)
  22. return true
  23. } catch {
  24. return false
  25. }
  26. }
  27. /**
  28. * Gets the ancestor process chain for a given process (up to maxDepth levels)
  29. * @param pid - The starting process ID
  30. * @param maxDepth - Maximum number of ancestors to fetch (default: 10)
  31. * @returns Array of ancestor PIDs from immediate parent to furthest ancestor
  32. */
  33. export async function getAncestorPidsAsync(
  34. pid: string | number,
  35. maxDepth = 10,
  36. ): Promise<number[]> {
  37. if (process.platform === 'win32') {
  38. // For Windows, use a PowerShell script that walks the process tree
  39. const script = `
  40. $pid = ${String(pid)}
  41. $ancestors = @()
  42. for ($i = 0; $i -lt ${maxDepth}; $i++) {
  43. $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$pid" -ErrorAction SilentlyContinue
  44. if (-not $proc -or -not $proc.ParentProcessId -or $proc.ParentProcessId -eq 0) { break }
  45. $pid = $proc.ParentProcessId
  46. $ancestors += $pid
  47. }
  48. $ancestors -join ','
  49. `.trim()
  50. const result = await execFileNoThrowWithCwd(
  51. 'powershell.exe',
  52. ['-NoProfile', '-Command', script],
  53. { timeout: 3000 },
  54. )
  55. if (result.code !== 0 || !result.stdout?.trim()) {
  56. return []
  57. }
  58. return result.stdout
  59. .trim()
  60. .split(',')
  61. .filter(Boolean)
  62. .map(p => parseInt(p, 10))
  63. .filter(p => !isNaN(p))
  64. }
  65. // For Unix, use a shell command that walks up the process tree
  66. // This uses a single process invocation instead of multiple sequential calls
  67. const script = `pid=${String(pid)}; for i in $(seq 1 ${maxDepth}); do ppid=$(ps -o ppid= -p $pid 2>/dev/null | tr -d ' '); if [ -z "$ppid" ] || [ "$ppid" = "0" ] || [ "$ppid" = "1" ]; then break; fi; echo $ppid; pid=$ppid; done`
  68. const result = await execFileNoThrowWithCwd('sh', ['-c', script], {
  69. timeout: 3000,
  70. })
  71. if (result.code !== 0 || !result.stdout?.trim()) {
  72. return []
  73. }
  74. return result.stdout
  75. .trim()
  76. .split('\n')
  77. .filter(Boolean)
  78. .map(p => parseInt(p, 10))
  79. .filter(p => !isNaN(p))
  80. }
  81. /**
  82. * Gets the command line for a given process
  83. * @param pid - The process ID to get the command for
  84. * @returns The command line string, or null if not found
  85. * @deprecated Use getAncestorCommandsAsync instead
  86. */
  87. export function getProcessCommand(pid: string | number): string | null {
  88. try {
  89. const pidStr = String(pid)
  90. const command =
  91. process.platform === 'win32'
  92. ? `powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId=${pidStr}\\").CommandLine"`
  93. : `ps -o command= -p ${pidStr}`
  94. const result = execSyncWithDefaults_DEPRECATED(command, { timeout: 1000 })
  95. return result ? result.trim() : null
  96. } catch {
  97. return null
  98. }
  99. }
  100. /**
  101. * Gets the command lines for a process and its ancestors in a single call
  102. * @param pid - The starting process ID
  103. * @param maxDepth - Maximum depth to traverse (default: 10)
  104. * @returns Array of command strings for the process chain
  105. */
  106. export async function getAncestorCommandsAsync(
  107. pid: string | number,
  108. maxDepth = 10,
  109. ): Promise<string[]> {
  110. if (process.platform === 'win32') {
  111. // For Windows, use a PowerShell script that walks the process tree and collects commands
  112. const script = `
  113. $currentPid = ${String(pid)}
  114. $commands = @()
  115. for ($i = 0; $i -lt ${maxDepth}; $i++) {
  116. $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$currentPid" -ErrorAction SilentlyContinue
  117. if (-not $proc) { break }
  118. if ($proc.CommandLine) { $commands += $proc.CommandLine }
  119. if (-not $proc.ParentProcessId -or $proc.ParentProcessId -eq 0) { break }
  120. $currentPid = $proc.ParentProcessId
  121. }
  122. $commands -join [char]0
  123. `.trim()
  124. const result = await execFileNoThrowWithCwd(
  125. 'powershell.exe',
  126. ['-NoProfile', '-Command', script],
  127. { timeout: 3000 },
  128. )
  129. if (result.code !== 0 || !result.stdout?.trim()) {
  130. return []
  131. }
  132. return result.stdout.split('\0').filter(Boolean)
  133. }
  134. // For Unix, use a shell command that walks up the process tree and collects commands
  135. // Using null byte as separator to handle commands with newlines
  136. const script = `currentpid=${String(pid)}; for i in $(seq 1 ${maxDepth}); do cmd=$(ps -o command= -p $currentpid 2>/dev/null); if [ -n "$cmd" ]; then printf '%s\\0' "$cmd"; fi; ppid=$(ps -o ppid= -p $currentpid 2>/dev/null | tr -d ' '); if [ -z "$ppid" ] || [ "$ppid" = "0" ] || [ "$ppid" = "1" ]; then break; fi; currentpid=$ppid; done`
  137. const result = await execFileNoThrowWithCwd('sh', ['-c', script], {
  138. timeout: 3000,
  139. })
  140. if (result.code !== 0 || !result.stdout?.trim()) {
  141. return []
  142. }
  143. return result.stdout.split('\0').filter(Boolean)
  144. }
  145. /**
  146. * Gets the child process IDs for a given process
  147. * @param pid - The parent process ID
  148. * @returns Array of child process IDs as numbers
  149. */
  150. export function getChildPids(pid: string | number): number[] {
  151. try {
  152. const pidStr = String(pid)
  153. const command =
  154. process.platform === 'win32'
  155. ? `powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ParentProcessId=${pidStr}\\").ProcessId"`
  156. : `pgrep -P ${pidStr}`
  157. const result = execSyncWithDefaults_DEPRECATED(command, { timeout: 1000 })
  158. if (!result) {
  159. return []
  160. }
  161. return result
  162. .trim()
  163. .split('\n')
  164. .filter(Boolean)
  165. .map(p => parseInt(p, 10))
  166. .filter(p => !isNaN(p))
  167. } catch {
  168. return []
  169. }
  170. }