Background agents/tasks not cleaned up, causing 100% memory usage
Resolved 💬 3 comments Opened Jan 19, 2026 by kareemassad Closed Jan 23, 2026
Description
When using background tasks (run_in_background: true with Bash tool or Task tool with background agents), child processes are not properly cleaned up when:
- The task completes but
TaskOutputis never called to retrieve results - The session ends or conversation switches before output is retrieved
- There's an error during execution
These orphaned processes continue running and consuming memory, eventually leading to 100% memory usage.
Steps to Reproduce
- Start a Claude Code session
- Run a long-running command with
run_in_background: true:
````
Bash tool with run_in_background: true
command: "npm test -- --testPathPattern='some-pattern' --testTimeout=30000"
- Either:
- End the session before calling
TaskOutput - Switch to a different conversation
- Let the command complete but don't retrieve output
Expected Behavior
Child processes spawned by background tasks should be:
- Tracked by the parent Claude process
- Terminated when the session ends
- Cleaned up if
TaskOutputis never called (with a reasonable timeout)
Actual Behavior
- Child processes become orphaned (PPID changes or parent exits)
- Processes continue running indefinitely
- Memory usage grows unbounded
- Task output files in
/private/tmp/claude/*/tasks/remain as 0-byte files
Evidence
Task output directory shows incomplete tasks (0-byte files):
$ ls -la /private/tmp/claude/-Users-*/tasks/
-rw-r--r-- 1 user wheel 2551 Jan 19 15:15 b12ce7a.output # completed
-rw-r--r-- 1 user wheel 0 Jan 19 15:12 b15840a.output # orphaned
-rw-r--r-- 1 user wheel 0 Jan 19 15:06 b5dbd8d.output # orphaned
-rw-r--r-- 1 user wheel 2273 Jan 19 15:10 b6cfad7.output # completed
-rw-r--r-- 1 user wheel 0 Jan 19 15:04 b82d28e.output # orphaned
-rw-r--r-- 1 user wheel 0 Jan 19 15:03 bea612e.output # orphaned
Environment
- OS: macOS (Darwin 25.2.0)
- Claude Code version: 2.1.12
- Shell: zsh
Suggested Fix
- Register child processes in a process group
- Set up SIGTERM/SIGINT handlers to clean up child processes on session end
- Implement a timeout mechanism for background tasks that auto-terminates after N minutes if output isn't retrieved
- Consider using
process.on('exit', cleanup)to ensure cleanup on normal exit
Workaround
Users can manually clean up orphaned processes:
# Kill orphaned test runners
pkill -f "vitest run"
pkill -f "tsx scripts"
# Clean up old task files
find /private/tmp/claude -name "*.output" -mmin +60 -deleteThis issue has 3 comments on GitHub. Read the full discussion on GitHub ↗