Cross-platform utility for terminating process trees by killing a parent process and all its descendant processes
npx @tessl/cli install tessl/npm-tree-kill@1.2.00
# Tree Kill
1
2
Tree Kill is a cross-platform Node.js library for terminating process trees by killing a parent process and all its descendant processes. It provides platform-specific implementations for Linux, macOS/Darwin, and Windows, offering both programmatic API and command-line interface with security features to prevent code injection vulnerabilities.
3
4
## Package Information
5
6
- **Package Name**: tree-kill
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install tree-kill`
10
11
## Core Imports
12
13
```javascript
14
const kill = require('tree-kill');
15
```
16
17
ES Modules:
18
19
```javascript
20
import kill from 'tree-kill';
21
```
22
23
TypeScript:
24
25
```typescript
26
import kill from 'tree-kill';
27
```
28
29
## Basic Usage
30
31
```javascript
32
const kill = require('tree-kill');
33
34
// Kill a process tree with default SIGTERM signal
35
kill(1234);
36
37
// Kill with a specific signal
38
kill(1234, 'SIGKILL');
39
40
// Kill with callback for error handling
41
kill(1234, 'SIGTERM', function(err) {
42
if (err) {
43
console.log('Error:', err.message);
44
} else {
45
console.log('Process tree killed successfully');
46
}
47
});
48
49
// Kill with callback but default signal
50
kill(1234, function(err) {
51
if (err) {
52
console.log('Error:', err.message);
53
} else {
54
console.log('Process tree killed successfully');
55
}
56
});
57
```
58
59
## Architecture
60
61
Tree Kill uses platform-specific process management commands to build and terminate process trees:
62
63
- **Linux**: Uses `ps -o pid --no-headers --ppid PID` to discover child processes
64
- **macOS/Darwin**: Uses `pgrep -P PID` to find child processes
65
- **Windows**: Uses `taskkill /pid PID /T /F` to kill the entire process tree at once
66
67
The library builds a complete process tree by recursively discovering all descendant processes, then systematically terminates them to ensure no orphaned processes remain.
68
69
## Capabilities
70
71
### Process Tree Termination
72
73
Kills a process and all its descendant processes across different operating systems.
74
75
```javascript { .api }
76
/**
77
* Kills process identified by pid and all its children
78
* @param pid - Process ID to kill (required)
79
* @param signal - Signal to send (optional, defaults to 'SIGTERM')
80
* @param callback - Error-first callback (optional)
81
*/
82
function kill(pid: number, callback?: (error?: Error) => void): void;
83
function kill(pid: number, signal?: string | number, callback?: (error?: Error) => void): void;
84
```
85
86
**Parameters:**
87
- `pid` (number): The process ID of the root process to kill. Must be a valid integer.
88
- `signal` (string | number | null, optional): The signal to send to processes. Defaults to `'SIGTERM'`. Can be any valid Node.js process signal (e.g., `'SIGKILL'`, `'SIGINT'`, `9`, `15`) or `null` to use the default signal.
89
- `callback` (function, optional): Error-first callback function called when the operation completes. Signature: `(error?: Error) => void`.
90
91
**Behavior:**
92
- Validates that `pid` is a number; throws/returns error if not
93
- Discovers all descendant processes using platform-specific commands
94
- Kills all processes in the tree, starting with children then parent
95
- On Windows, uses `taskkill` which handles the entire tree atomically
96
- On Unix-like systems, recursively discovers and kills each process individually
97
- Ignores `ESRCH` errors (process not found) as processes may exit during tree traversal
98
99
**Error Handling:**
100
- Throws `Error("pid must be a number")` if `pid` is not a valid number (when no callback provided)
101
- Calls callback with error if `pid` validation fails (when callback provided)
102
- Handles process-not-found errors gracefully during tree killing
103
- Platform-specific command failures are handled appropriately
104
105
**Usage Examples:**
106
107
```javascript
108
const kill = require('tree-kill');
109
110
// Basic usage - kill with default SIGTERM
111
kill(1234);
112
113
// Kill with specific signal
114
kill(1234, 'SIGKILL');
115
kill(1234, 9); // Same as SIGKILL
116
117
// Async usage with callback
118
kill(1234, function(err) {
119
if (err) {
120
console.error('Failed to kill process tree:', err.message);
121
} else {
122
console.log('Process tree terminated successfully');
123
}
124
});
125
126
// Kill with specific signal and callback
127
kill(1234, 'SIGTERM', function(err) {
128
if (err) {
129
console.error('Kill failed:', err.message);
130
} else {
131
console.log('Process tree killed with SIGTERM');
132
}
133
});
134
135
// Kill with null signal (uses default) and callback
136
kill(1234, null, function(err) {
137
if (err) {
138
console.error('Kill failed:', err.message);
139
} else {
140
console.log('Process tree killed with default signal');
141
}
142
});
143
144
// Error handling for invalid PID
145
try {
146
kill('invalid-pid');
147
} catch (err) {
148
console.error('Invalid PID:', err.message);
149
}
150
151
// Async error handling for invalid PID
152
kill('invalid-pid', function(err) {
153
if (err) {
154
console.error('Invalid PID:', err.message);
155
}
156
});
157
```
158
159
### Command Line Interface
160
161
Tree Kill provides a command-line interface for process tree termination.
162
163
```bash { .api }
164
# Kill process tree with default SIGTERM signal
165
tree-kill <pid>
166
167
# Kill process tree with specific signal
168
tree-kill <pid> <signal>
169
```
170
171
**Parameters:**
172
- `<pid>`: Process ID to kill (required)
173
- `<signal>`: Signal to send (optional, defaults to SIGTERM)
174
175
**Examples:**
176
177
```bash
178
# Kill process 1234 and its children with SIGTERM
179
tree-kill 1234
180
181
# Kill process 1234 and its children with SIGKILL
182
tree-kill 1234 SIGKILL
183
184
# Kill with numeric signal
185
tree-kill 1234 9
186
```
187
188
**Error Handling:**
189
- Exits with status code 1 on error
190
- Prints error messages to console
191
- Handles both synchronous errors (invalid PID) and asynchronous errors (kill failures)
192
193
## Platform-Specific Behavior
194
195
### Linux
196
- Uses `ps -o pid --no-headers --ppid PID` to find child processes
197
- Recursively builds process tree by querying each parent
198
- Kills processes individually using Node.js `process.kill()`
199
- Handles ESRCH errors gracefully when processes exit during traversal
200
201
### macOS/Darwin
202
- Uses `pgrep -P PID` to find child processes
203
- Same recursive tree building and individual killing as Linux
204
- Optimized for macOS process management utilities
205
206
### Windows
207
- Uses `taskkill /pid PID /T /F` command
208
- `/T` flag kills the process tree (parent and all descendants)
209
- `/F` flag forces termination
210
- Atomic operation - entire tree killed in one command
211
- Note: POSIX signal differentiation not supported on Windows
212
213
## Security Features
214
215
- **PID Validation**: Strictly validates PID parameter to prevent code injection
216
- **Integer Parsing**: Converts PID to integer and validates it's a number
217
- **Command Safety**: Uses child_process.spawn/exec with validated parameters only
218
- **Input Sanitization**: Security fix in v1.2.2 prevents arbitrary code execution vulnerabilities
219
220
## Error Types
221
222
```javascript { .api }
223
interface TreeKillError extends Error {
224
message: string;
225
code?: string; // May include system error codes like 'ESRCH'
226
}
227
```
228
229
**Common Errors:**
230
- `"pid must be a number"`: Invalid PID parameter provided
231
- `"ESRCH"`: Process not found (handled gracefully during tree killing)
232
- Platform-specific command execution errors (rare, usually indicate system issues)
233
234
## TypeScript Support
235
236
Tree Kill includes TypeScript definitions with function overloads for optional parameters:
237
238
```typescript { .api }
239
declare function treeKill(pid: number, callback?: (error?: Error) => void): void;
240
declare function treeKill(pid: number, signal?: string | number, callback?: (error?: Error) => void): void;
241
242
declare namespace treeKill {}
243
244
export = treeKill;
245
```