{"record":{"id":"dafbc1b73b08acc2","repo":"thedotmack/claude-mem","slug":"taskkill-failed-for-pid-pid-exit-string-code","errorCode":null,"errorMessage":"taskkill failed for PID ${pid} (exit ${String(code)}): ${stderr.trim() || message}","messagePattern":"taskkill failed for PID (.+?) \\(exit (.+?)\\): (.+?)","errorType":"exception","errorClass":"ProcessTreeKillError","httpStatus":null,"severity":"error","filePath":"src/shared/kill-process-tree.ts","lineNumber":158,"sourceCode":"      await execFileAsync('taskkill', ['/PID', String(pid), '/T', '/F'], {\n        timeout: 5_000,\n        windowsHide: true\n      });\n    } catch (error) {\n      const code = (error as { code?: number | string }).code;\n      const stderr = String((error as { stderr?: unknown }).stderr ?? '');\n      const message = error instanceof Error ? error.message : String(error);\n\n      // Already gone is the expected, tolerated case.\n      if (code === TASKKILL_NOT_FOUND_EXIT || TASKKILL_NOT_FOUND_PATTERN.test(`${stderr} ${message}`)) {\n        logger.debug('PROCESS', 'taskkill reported the process was already gone', { pid });\n        return;\n      }\n\n      // Anything else — access denied, a timeout, a wedged /T walk — means the\n      // tree may still be running. Surfacing it is the whole point: callers\n      // like `server stop` must not report success over a failed kill.\n      throw new ProcessTreeKillError(\n        pid,\n        `taskkill failed for PID ${pid} (exit ${String(code)}): ${stderr.trim() || message}`,\n        { cause: error }\n      );\n    }\n    return;\n  }\n\n  // POSIX: walk descendants recursively (bottom-up) and signal each.\n  // `pkill -P <pid>` only reaches direct children, so `python` /\n  // `chroma-mcp` under `uv` (grandchildren) get re-parented to init and\n  // survive. We collect the full descendant set via `pgrep -P` walks before\n  // signaling, so the SIGTERM phase reaches every layer\n  // (CodeRabbit review on PR #2282).\n  try {\n    const firstSignal: NodeJS.Signals = immediate ? 'SIGKILL' : 'SIGTERM';\n    const descendantsBeforeTerm = await collectDescendantIdentities(pid);\n    // Signal leaves first, then the root.","sourceCodeStart":140,"sourceCodeEnd":176,"githubUrl":"https://github.com/thedotmack/claude-mem/blob/d8bc9755e74915e5c3b999181e10a67c889bce2a/src/shared/kill-process-tree.ts#L140-L176","documentation":"On Windows, killProcessTree uses `taskkill /PID <pid> /T /F`. taskkill's 'process not found' outcome is tolerated, but any other failure — access denied, the 5s timeout, a wedged /T walk — is raised as a ProcessTreeKillError because the tree may still be alive and callers (e.g. `server stop`) must not report success over a failed kill.","triggerScenarios":"process.platform === 'win32' and execFileAsync('taskkill', ...) rejects with an exit code other than the not-found code and stderr not matching the not-found pattern: access denied on a protected process, the 5000ms timeout expiring, or taskkill failing while walking the tree.","commonSituations":"Killing a service/elevated process from a non-elevated shell; antivirus or the OS holding the process during teardown; a deep/locked child tree making taskkill exceed its timeout.","solutions":["Re-run the kill from an elevated (Administrator) shell if the stderr says access denied","Check whether the PID is actually dead (`tasklist | findstr <pid>`); if it survived, kill it manually with `taskkill /PID <pid> /T /F` and investigate why it was protected","Retry killProcessTree once — transient timeouts/wedged walks often succeed on a second attempt; handle ProcessTreeKillError explicitly in callers"],"exampleFix":"// before\ncleanupUnexpectedCloseSubprocess(child); // assumed success\n\n// after\ntry {\n  await cleanupUnexpectedCloseSubprocess(child);\n} catch (e) {\n  if (e instanceof ProcessTreeKillError) logger.warn('tree may still be running', { pid: e.pid });\n  throw e;\n}","handlingStrategy":"try-catch","validationCode":"import { execFile } from 'child_process';\n// Windows pre-check: is the PID still there before attempting teardown?\nexecFile('tasklist', ['/FI', `PID eq ${pid}`], (err, stdout) => {\n  if (!stdout.includes(String(pid))) console.log('already gone; skip taskkill');\n});","typeGuard":"function isProcessTreeKillError(e: unknown): e is ProcessTreeKillError {\n  return e instanceof ProcessTreeKillError;\n}","tryCatchPattern":"try {\n  await killProcessTree(pid);\n} catch (e) {\n  if (isProcessTreeKillError(e)) {\n    logger.warn(`kill may have failed for ${e.pid}; tree may still be running`, { cause: e.cause });\n  } else throw e;\n}","preventionTips":["Run kill/teardown flows from an appropriately privileged shell on Windows","Treat ProcessTreeKillError as 'tree may still be alive' and verify with tasklist","Avoid killing protected/elevated processes from non-elevated services"],"tags":["windows","process-kill","taskkill"],"backgroundTag":"process-kill-failed","analyzedSha":"d8bc9755e74915e5c3b999181e10a67c889bce2a","analyzedAt":"2026-09-17T16:40:26.182Z","contentChangedAt":"2026-09-17T16:40:26.182Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}