Merge remote-tracking branch 'ry/v0.6' into master
[platform/upstream/nodejs.git] / doc / api / child_process.markdown
1 # Child Process
2
3     Stability: 3 - Stable
4
5 Node provides a tri-directional `popen(3)` facility through the
6 `child_process` module.
7
8 It is possible to stream data through a child's `stdin`, `stdout`, and
9 `stderr` in a fully non-blocking way.
10
11 To create a child process use `require('child_process').spawn()` or
12 `require('child_process').fork()`.  The semantics of each are slightly
13 different, and explained below.
14
15 ## Class: ChildProcess
16
17 `ChildProcess` is an `EventEmitter`.
18
19 Child processes always have three streams associated with them. `child.stdin`,
20 `child.stdout`, and `child.stderr`.  These may be shared with the stdio
21 streams of the parent process, or they may be separate stream objects
22 which can be piped to and from.
23
24 The ChildProcess class is not intended to be used directly.  Use the
25 `spawn()` or `fork()` methods to create a Child Process instance.
26
27 ### Event:  'exit'
28
29 * `code` {Number} the exit code, if it exited normally.
30 * `signal` {String} the signal passed to kill the child process, if it
31   was killed by the parent.
32
33 This event is emitted after the child process ends. If the process terminated
34 normally, `code` is the final exit code of the process, otherwise `null`. If
35 the process terminated due to receipt of a signal, `signal` is the string name
36 of the signal, otherwise `null`.
37
38 Note that the child process stdio streams might still be open.
39
40 See `waitpid(2)`.
41
42 ### Event: 'close'
43
44 This event is emitted when the stdio streams of a child process have all
45 terminated.  This is distinct from 'exit', since multiple processes
46 might share the same stdio streams.
47
48 ### Event: 'disconnect'
49
50 This event is emitted after using the `.disconnect()` method in the parent or
51 in the child. After disconnecting it is no longer possible to send messages.
52 An alternative way to check if you can send messages is to see if the
53 `child.connected` property is `true`.
54
55 ### child.stdin
56
57 * {Stream object}
58
59 A `Writable Stream` that represents the child process's `stdin`.
60 Closing this stream via `end()` often causes the child process to terminate.
61
62 If the child stdio streams are shared with the parent, then this will
63 not be set.
64
65 ### child.stdout
66
67 * {Stream object}
68
69 A `Readable Stream` that represents the child process's `stdout`.
70
71 If the child stdio streams are shared with the parent, then this will
72 not be set.
73
74 ### child.stderr
75
76 * {Stream object}
77
78 A `Readable Stream` that represents the child process's `stderr`.
79
80 If the child stdio streams are shared with the parent, then this will
81 not be set.
82
83 ### child.pid
84
85 * {Integer}
86
87 The PID of the child process.
88
89 Example:
90
91     var spawn = require('child_process').spawn,
92         grep  = spawn('grep', ['ssh']);
93
94     console.log('Spawned child pid: ' + grep.pid);
95     grep.stdin.end();
96
97 ### child.kill([signal])
98
99 * `signal` {String}
100
101 Send a signal to the child process. If no argument is given, the process will
102 be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
103
104     var spawn = require('child_process').spawn,
105         grep  = spawn('grep', ['ssh']);
106
107     grep.on('exit', function (code, signal) {
108       console.log('child process terminated due to receipt of signal '+signal);
109     });
110
111     // send SIGHUP to process
112     grep.kill('SIGHUP');
113
114 Note that while the function is called `kill`, the signal delivered to the child
115 process may not actually kill it.  `kill` really just sends a signal to a process.
116
117 See `kill(2)`
118
119
120 ### child.send(message, [sendHandle])
121
122 * `message` {Object}
123 * `sendHandle` {Handle object}
124
125 Send a message (and, optionally, a handle object) to a child process.
126
127 See `child_process.fork()` for details.
128
129 ## child_process.spawn(command, [args], [options])
130
131 * `command` {String} The command to run
132 * `args` {Array} List of string arguments
133 * `options` {Object}
134   * `cwd` {String} Current working directory of the child process
135   * `customFds` {Array} **Deprecated** File descriptors for the child to use
136     for stdio.  (See below)
137   * `env` {Object} Environment key-value pairs
138   * `setsid` {Boolean}
139 * return: {ChildProcess object}
140
141 Launches a new process with the given `command`, with  command line arguments in `args`.
142 If omitted, `args` defaults to an empty Array.
143
144 The third argument is used to specify additional options, which defaults to:
145
146     { cwd: undefined,
147       env: process.env
148     }
149
150 `cwd` allows you to specify the working directory from which the process is spawned.
151 Use `env` to specify environment variables that will be visible to the new process.
152
153 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
154
155     var util  = require('util'),
156         spawn = require('child_process').spawn,
157         ls    = spawn('ls', ['-lh', '/usr']);
158
159     ls.stdout.on('data', function (data) {
160       console.log('stdout: ' + data);
161     });
162
163     ls.stderr.on('data', function (data) {
164       console.log('stderr: ' + data);
165     });
166
167     ls.on('exit', function (code) {
168       console.log('child process exited with code ' + code);
169     });
170
171
172 Example: A very elaborate way to run 'ps ax | grep ssh'
173
174     var util  = require('util'),
175         spawn = require('child_process').spawn,
176         ps    = spawn('ps', ['ax']),
177         grep  = spawn('grep', ['ssh']);
178
179     ps.stdout.on('data', function (data) {
180       grep.stdin.write(data);
181     });
182
183     ps.stderr.on('data', function (data) {
184       console.log('ps stderr: ' + data);
185     });
186
187     ps.on('exit', function (code) {
188       if (code !== 0) {
189         console.log('ps process exited with code ' + code);
190       }
191       grep.stdin.end();
192     });
193
194     grep.stdout.on('data', function (data) {
195       console.log(data);
196     });
197
198     grep.stderr.on('data', function (data) {
199       console.log('grep stderr: ' + data);
200     });
201
202     grep.on('exit', function (code) {
203       if (code !== 0) {
204         console.log('grep process exited with code ' + code);
205       }
206     });
207
208
209 Example of checking for failed exec:
210
211     var spawn = require('child_process').spawn,
212         child = spawn('bad_command');
213
214     child.stderr.setEncoding('utf8');
215     child.stderr.on('data', function (data) {
216       if (/^execvp\(\)/.test(data)) {
217         console.log('Failed to start child process.');
218       }
219     });
220
221 Note that if spawn receives an empty options object, it will result in
222 spawning the process with an empty environment rather than using
223 `process.env`. This due to backwards compatibility issues with a deprecated
224 API.
225
226 There is a deprecated option called `customFds` which allows one to specify
227 specific file descriptors for the stdio of the child process. This API was
228 not portable to all platforms and therefore removed.
229 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
230 stderr]` to existing streams; `-1` meant that a new stream should be created.
231 Use at your own risk.
232
233 There are several internal options. In particular `stdinStream`,
234 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
235 undocumented APIs in Node, they should not be used.
236
237 See also: `child_process.exec()` and `child_process.fork()`
238
239 ## child_process.exec(command, [options], callback)
240
241 * `command` {String} The command to run, with space-separated arguments
242 * `options` {Object}
243   * `cwd` {String} Current working directory of the child process
244   * `customFds` {Array} **Deprecated** File descriptors for the child to use
245     for stdio.  (See below)
246   * `env` {Object} Environment key-value pairs
247   * `setsid` {Boolean}
248   * `encoding` {String} (Default: 'utf8')
249   * `timeout` {Number} (Default: 0)
250   * `maxBuffer` {Number} (Default: 200*1024)
251   * `killSignal` {String} (Default: 'SIGTERM')
252 * `callback` {Function} called with the output when process terminates
253   * `code` {Integer} Exit code
254   * `stdout` {Buffer}
255   * `stderr` {Buffer}
256 * Return: ChildProcess object
257
258 Runs a command in a shell and buffers the output.
259
260     var util = require('util'),
261         exec = require('child_process').exec,
262         child;
263
264     child = exec('cat *.js bad_file | wc -l',
265       function (error, stdout, stderr) {
266         console.log('stdout: ' + stdout);
267         console.log('stderr: ' + stderr);
268         if (error !== null) {
269           console.log('exec error: ' + error);
270         }
271     });
272
273 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
274 will be `null`.  On error, `error` will be an instance of `Error` and `err.code`
275 will be the exit code of the child process, and `err.signal` will be set to the
276 signal that terminated the process.
277
278 There is a second optional argument to specify several options. The
279 default options are
280
281     { encoding: 'utf8',
282       timeout: 0,
283       maxBuffer: 200*1024,
284       killSignal: 'SIGTERM',
285       cwd: null,
286       env: null }
287
288 If `timeout` is greater than 0, then it will kill the child process
289 if it runs longer than `timeout` milliseconds. The child process is killed with
290 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
291 amount of data allowed on stdout or stderr - if this value is exceeded then
292 the child process is killed.
293
294
295 ## child_process.execFile(file, args, options, callback)
296
297 * `file` {String} The filename of the program to run
298 * `args` {Array} List of string arguments
299 * `options` {Object}
300   * `cwd` {String} Current working directory of the child process
301   * `customFds` {Array} **Deprecated** File descriptors for the child to use
302     for stdio.  (See below)
303   * `env` {Object} Environment key-value pairs
304   * `setsid` {Boolean}
305   * `encoding` {String} (Default: 'utf8')
306   * `timeout` {Number} (Default: 0)
307   * `maxBuffer` {Number} (Default: 200*1024)
308   * `killSignal` {String} (Default: 'SIGTERM')
309 * `callback` {Function} called with the output when process terminates
310   * `code` {Integer} Exit code
311   * `stdout` {Buffer}
312   * `stderr` {Buffer}
313 * Return: ChildProcess object
314
315 This is similar to `child_process.exec()` except it does not execute a
316 subshell but rather the specified file directly. This makes it slightly
317 leaner than `child_process.exec`. It has the same options.
318
319
320 ## child_process.fork(modulePath, [args], [options])
321
322 * `modulePath` {String} The module to run in the child
323 * `args` {Array} List of string arguments
324 * `options` {Object}
325   * `cwd` {String} Current working directory of the child process
326   * `customFds` {Array} **Deprecated** File descriptors for the child to use
327     for stdio.  (See below)
328   * `env` {Object} Environment key-value pairs
329   * `setsid` {Boolean}
330   * `encoding` {String} (Default: 'utf8')
331   * `timeout` {Number} (Default: 0)
332 * `callback` {Function} called with the output when process terminates
333   * `code` {Integer} Exit code
334   * `stdout` {Buffer}
335   * `stderr` {Buffer}
336 * Return: ChildProcess object
337
338 This is a special case of the `spawn()` functionality for spawning Node
339 processes. In addition to having all the methods in a normal ChildProcess
340 instance, the returned object has a communication channel built-in. The
341 channel is written to with `child.send(message, [sendHandle])` and messages
342 are received by a `'message'` event on the child.
343
344 For example:
345
346     var cp = require('child_process');
347
348     var n = cp.fork(__dirname + '/sub.js');
349
350     n.on('message', function(m) {
351       console.log('PARENT got message:', m);
352     });
353
354     n.send({ hello: 'world' });
355
356 And then the child script, `'sub.js'` might look like this:
357
358     process.on('message', function(m) {
359       console.log('CHILD got message:', m);
360     });
361
362     process.send({ foo: 'bar' });
363
364 In the child the `process` object will have a `send()` method, and `process`
365 will emit objects each time it receives a message on its channel.
366
367 There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
368 containing a `NODE_` prefix in its `cmd` property will not be emitted in
369 the `message` event, since they are internal messages used by node core.
370 Messages containing the prefix are emitted in the `internalMessage` event, you
371 should by all means avoid using this feature, it may change without warranty.
372
373 By default the spawned Node process will have the stdout, stderr associated
374 with the parent's. To change this behavior set the `silent` property in the
375 `options` object to `true`.
376
377 These child Nodes are still whole new instances of V8. Assume at least 30ms
378 startup and 10mb memory for each new Node. That is, you cannot create many
379 thousands of them.
380
381 The `sendHandle` option to `child.send()` is for sending a handle object to
382 another process. Child will receive the handle as as second argument to the
383 `message` event. Here is an example of sending a handle:
384
385     var server = require('net').createServer();
386     var child = require('child_process').fork(__dirname + '/child.js');
387     // Open up the server object and send the handle.
388     server.listen(1337, function() {
389       child.send({ server: true }, server._handle);
390     });
391
392 Here is an example of receiving the server handle and sharing it between
393 processes:
394
395     process.on('message', function(m, serverHandle) {
396       if (serverHandle) {
397         var server = require('net').createServer();
398         server.listen(serverHandle);
399       }
400     });
401
402 To close the IPC connection between parent and child use the
403 `child.disconnect()` method. This allows the child to exit gracefully since
404 there is no IPC channel keeping it alive. When calling this method the
405 `disconnect` event will be emitted in both parent and child, and the
406 `connected` flag will be set to `false`. Please note that you can also call
407 `process.disconnect()` in the child process.