Merge remote-tracking branch 'ry/v0.8' 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.  (Note that some programs use
10 line-buffered I/O internally.  That doesn't affect node.js but it means
11 data you send to the child process is not immediately consumed.)
12
13 To create a child process use `require('child_process').spawn()` or
14 `require('child_process').fork()`.  The semantics of each are slightly
15 different, and explained below.
16
17 ## Class: ChildProcess
18
19 `ChildProcess` is an [EventEmitter][].
20
21 Child processes always have three streams associated with them. `child.stdin`,
22 `child.stdout`, and `child.stderr`.  These may be shared with the stdio
23 streams of the parent process, or they may be separate stream objects
24 which can be piped to and from.
25
26 The ChildProcess class is not intended to be used directly.  Use the
27 `spawn()` or `fork()` methods to create a Child Process instance.
28
29 ### Event:  'exit'
30
31 * `code` {Number} the exit code, if it exited normally.
32 * `signal` {String} the signal passed to kill the child process, if it
33   was killed by the parent.
34
35 This event is emitted after the child process ends. If the process terminated
36 normally, `code` is the final exit code of the process, otherwise `null`. If
37 the process terminated due to receipt of a signal, `signal` is the string name
38 of the signal, otherwise `null`.
39
40 Note that the child process stdio streams might still be open.
41
42 See `waitpid(2)`.
43
44 ### Event: 'close'
45
46 * `code` {Number} the exit code, if it exited normally.
47 * `signal` {String} the signal passed to kill the child process, if it
48   was killed by the parent.
49
50 This event is emitted when the stdio streams of a child process have all
51 terminated.  This is distinct from 'exit', since multiple processes
52 might share the same stdio streams.
53
54 ### Event: 'disconnect'
55
56 This event is emitted after using the `.disconnect()` method in the parent or
57 in the child. After disconnecting it is no longer possible to send messages.
58 An alternative way to check if you can send messages is to see if the
59 `child.connected` property is `true`.
60
61 ### Event: 'message'
62
63 * `message` {Object} a parsed JSON object or primitive value
64 * `sendHandle` {Handle object} a Socket or Server object
65
66 Messages send by `.send(message, [sendHandle])` are obtained using the
67 `message` event.
68
69 ### child.stdin
70
71 * {Stream object}
72
73 A `Writable Stream` that represents the child process's `stdin`.
74 Closing this stream via `end()` often causes the child process to terminate.
75
76 If the child stdio streams are shared with the parent, then this will
77 not be set.
78
79 ### child.stdout
80
81 * {Stream object}
82
83 A `Readable Stream` that represents the child process's `stdout`.
84
85 If the child stdio streams are shared with the parent, then this will
86 not be set.
87
88 ### child.stderr
89
90 * {Stream object}
91
92 A `Readable Stream` that represents the child process's `stderr`.
93
94 If the child stdio streams are shared with the parent, then this will
95 not be set.
96
97 ### child.pid
98
99 * {Integer}
100
101 The PID of the child process.
102
103 Example:
104
105     var spawn = require('child_process').spawn,
106         grep  = spawn('grep', ['ssh']);
107
108     console.log('Spawned child pid: ' + grep.pid);
109     grep.stdin.end();
110
111 ### child.kill([signal])
112
113 * `signal` {String}
114
115 Send a signal to the child process. If no argument is given, the process will
116 be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
117
118     var spawn = require('child_process').spawn,
119         grep  = spawn('grep', ['ssh']);
120
121     grep.on('close', function (code, signal) {
122       console.log('child process terminated due to receipt of signal '+signal);
123     });
124
125     // send SIGHUP to process
126     grep.kill('SIGHUP');
127
128 Note that while the function is called `kill`, the signal delivered to the child
129 process may not actually kill it.  `kill` really just sends a signal to a process.
130
131 See `kill(2)`
132
133 ### child.send(message, [sendHandle])
134
135 * `message` {Object}
136 * `sendHandle` {Handle object}
137
138 When using `child_process.fork()` you can write to the child using
139 `child.send(message, [sendHandle])` and messages are received by
140 a `'message'` event on the child.
141
142 For example:
143
144     var cp = require('child_process');
145
146     var n = cp.fork(__dirname + '/sub.js');
147
148     n.on('message', function(m) {
149       console.log('PARENT got message:', m);
150     });
151
152     n.send({ hello: 'world' });
153
154 And then the child script, `'sub.js'` might look like this:
155
156     process.on('message', function(m) {
157       console.log('CHILD got message:', m);
158     });
159
160     process.send({ foo: 'bar' });
161
162 In the child the `process` object will have a `send()` method, and `process`
163 will emit objects each time it receives a message on its channel.
164
165 There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
166 containing a `NODE_` prefix in its `cmd` property will not be emitted in
167 the `message` event, since they are internal messages used by node core.
168 Messages containing the prefix are emitted in the `internalMessage` event, you
169 should by all means avoid using this feature, it is subject to change without notice.
170
171 The `sendHandle` option to `child.send()` is for sending a TCP server or
172 socket object to another process. The child will receive the object as its
173 second argument to the `message` event.
174
175 #### Example: sending server object
176
177 Here is an example of sending a server:
178
179     var child = require('child_process').fork('child.js');
180
181     // Open up the server object and send the handle.
182     var server = require('net').createServer();
183     server.on('connection', function (socket) {
184       socket.end('handled by parent');
185     });
186     server.listen(1337, function() {
187       child.send('server', server);
188     });
189
190 And the child would the receive the server object as:
191
192     process.on('message', function(m, server) {
193       if (m === 'server') {
194         server.on('connection', function (socket) {
195           socket.end('handled by child');
196         });
197       }
198     });
199
200 Note that the server is now shared between the parent and child, this means
201 that some connections will be handled by the parent and some by the child.
202
203 For `dgram` servers the workflow is exactly the same.  Here you listen on
204 a `message` event instead of `connection` and use `server.bind` instead of
205 `server.listen`.
206
207 #### Example: sending socket object
208
209 Here is an example of sending a socket. It will spawn two children and handle
210 connections with the remote address `74.125.127.100` as VIP by sending the
211 socket to a "special" child process. Other sockets will go to a "normal" process.
212
213     var normal = require('child_process').fork('child.js', ['normal']);
214     var special = require('child_process').fork('child.js', ['special']);
215
216     // Open up the server and send sockets to child
217     var server = require('net').createServer();
218     server.on('connection', function (socket) {
219
220       // if this is a VIP
221       if (socket.remoteAddress === '74.125.127.100') {
222         special.send('socket', socket);
223         return;
224       }
225       // just the usual dudes
226       normal.send('socket', socket);
227     });
228     server.listen(1337);
229
230 The `child.js` could look like this:
231
232     process.on('message', function(m, socket) {
233       if (m === 'socket') {
234         socket.end('You were handled as a ' + process.argv[2] + ' person');
235       }
236     });
237
238 Note that once a single socket has been sent to a child the parent can no
239 longer keep track of when the socket is destroyed. To indicate this condition
240 the `.connections` property becomes `null`.
241 It is also recommended not to use `.maxConnections` in this condition.
242
243 ### child.disconnect()
244
245 To close the IPC connection between parent and child use the
246 `child.disconnect()` method. This allows the child to exit gracefully since
247 there is no IPC channel keeping it alive. When calling this method the
248 `disconnect` event will be emitted in both parent and child, and the
249 `connected` flag will be set to `false`. Please note that you can also call
250 `process.disconnect()` in the child process.
251
252 ## child_process.spawn(command, [args], [options])
253
254 * `command` {String} The command to run
255 * `args` {Array} List of string arguments
256 * `options` {Object}
257   * `cwd` {String} Current working directory of the child process
258   * `stdio` {Array|String} Child's stdio configuration. (See below)
259   * `customFds` {Array} **Deprecated** File descriptors for the child to use
260     for stdio.  (See below)
261   * `env` {Object} Environment key-value pairs
262   * `detached` {Boolean} The child will be a process group leader.  (See below)
263   * `uid` {Number} Sets the user identity of the process. (See setuid(2).)
264   * `gid` {Number} Sets the group identity of the process. (See setgid(2).)
265 * return: {ChildProcess object}
266
267 Launches a new process with the given `command`, with  command line arguments in `args`.
268 If omitted, `args` defaults to an empty Array.
269
270 The third argument is used to specify additional options, which defaults to:
271
272     { cwd: undefined,
273       env: process.env
274     }
275
276 `cwd` allows you to specify the working directory from which the process is spawned.
277 Use `env` to specify environment variables that will be visible to the new process.
278
279 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
280
281     var spawn = require('child_process').spawn,
282         ls    = spawn('ls', ['-lh', '/usr']);
283
284     ls.stdout.on('data', function (data) {
285       console.log('stdout: ' + data);
286     });
287
288     ls.stderr.on('data', function (data) {
289       console.log('stderr: ' + data);
290     });
291
292     ls.on('close', function (code) {
293       console.log('child process exited with code ' + code);
294     });
295
296
297 Example: A very elaborate way to run 'ps ax | grep ssh'
298
299     var spawn = require('child_process').spawn,
300         ps    = spawn('ps', ['ax']),
301         grep  = spawn('grep', ['ssh']);
302
303     ps.stdout.on('data', function (data) {
304       grep.stdin.write(data);
305     });
306
307     ps.stderr.on('data', function (data) {
308       console.log('ps stderr: ' + data);
309     });
310
311     ps.on('close', function (code) {
312       if (code !== 0) {
313         console.log('ps process exited with code ' + code);
314       }
315       grep.stdin.end();
316     });
317
318     grep.stdout.on('data', function (data) {
319       console.log('' + data);
320     });
321
322     grep.stderr.on('data', function (data) {
323       console.log('grep stderr: ' + data);
324     });
325
326     grep.on('close', function (code) {
327       if (code !== 0) {
328         console.log('grep process exited with code ' + code);
329       }
330     });
331
332
333 Example of checking for failed exec:
334
335     var spawn = require('child_process').spawn,
336         child = spawn('bad_command');
337
338     child.stderr.setEncoding('utf8');
339     child.stderr.on('data', function (data) {
340       if (/^execvp\(\)/.test(data)) {
341         console.log('Failed to start child process.');
342       }
343     });
344
345 Note that if spawn receives an empty options object, it will result in
346 spawning the process with an empty environment rather than using
347 `process.env`. This due to backwards compatibility issues with a deprecated
348 API.
349
350 The 'stdio' option to `child_process.spawn()` is an array where each
351 index corresponds to a fd in the child.  The value is one of the following:
352
353 1. `'pipe'` - Create a pipe between the child process and the parent process.
354    The parent end of the pipe is exposed to the parent as a property on the
355    `child_process` object as `ChildProcess.stdio[fd]`. Pipes created for
356    fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
357    and ChildProcess.stderr, respectively.
358 2. `'ipc'` - Create an IPC channel for passing messages/file descriptors
359    between parent and child. A ChildProcess may have at most *one* IPC stdio
360    file descriptor. Setting this option enables the ChildProcess.send() method.
361    If the child writes JSON messages to this file descriptor, then this will
362    trigger ChildProcess.on('message').  If the child is a Node.js program, then
363    the presence of an IPC channel will enable process.send() and
364    process.on('message').
365 3. `'ignore'` - Do not set this file descriptor in the child. Note that Node
366    will always open fd 0 - 2 for the processes it spawns. When any of these is
367    ignored node will open `/dev/null` and attach it to the child's fd.
368 4. `Stream` object - Share a readable or writable stream that refers to a tty,
369    file, socket, or a pipe with the child process. The stream's underlying
370    file descriptor is duplicated in the child process to the fd that 
371    corresponds to the index in the `stdio` array.
372 5. Positive integer - The integer value is interpreted as a file descriptor 
373    that is is currently open in the parent process. It is shared with the child
374    process, similar to how `Stream` objects can be shared.
375 6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
376    words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
377    default is `'ignore'`.
378
379 As a shorthand, the `stdio` argument may also be one of the following
380 strings, rather than an array:
381
382 * `ignore` - `['ignore', 'ignore', 'ignore']`
383 * `pipe` - `['pipe', 'pipe', 'pipe']`
384 * `inherit` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]`
385
386 Example:
387
388     var spawn = require('child_process').spawn;
389
390     // Child will use parent's stdios
391     spawn('prg', [], { stdio: 'inherit' });
392
393     // Spawn child sharing only stderr
394     spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
395
396     // Open an extra fd=4, to interact with programs present a
397     // startd-style interface.
398     spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
399
400 If the `detached` option is set, the child process will be made the leader of a
401 new process group.  This makes it possible for the child to continue running 
402 after the parent exits.
403
404 By default, the parent will wait for the detached child to exit.  To prevent
405 the parent from waiting for a given `child`, use the `child.unref()` method,
406 and the parent's event loop will not include the child in its reference count.
407
408 Example of detaching a long-running process and redirecting its output to a
409 file:
410
411      var fs = require('fs'),
412          spawn = require('child_process').spawn,
413          out = fs.openSync('./out.log', 'a'),
414          err = fs.openSync('./out.log', 'a');
415
416      var child = spawn('prg', [], {
417        detached: true,
418        stdio: [ 'ignore', out, err ]
419      });
420
421      child.unref();
422
423 When using the `detached` option to start a long-running process, the process
424 will not stay running in the background unless it is provided with a `stdio`
425 configuration that is not connected to the parent.  If the parent's `stdio` is
426 inherited, the child will remain attached to the controlling terminal.
427
428 There is a deprecated option called `customFds` which allows one to specify
429 specific file descriptors for the stdio of the child process. This API was
430 not portable to all platforms and therefore removed.
431 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
432 stderr]` to existing streams; `-1` meant that a new stream should be created.
433 Use at your own risk.
434
435 There are several internal options. In particular `stdinStream`,
436 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
437 undocumented APIs in Node, they should not be used.
438
439 See also: `child_process.exec()` and `child_process.fork()`
440
441 ## child_process.exec(command, [options], callback)
442
443 * `command` {String} The command to run, with space-separated arguments
444 * `options` {Object}
445   * `cwd` {String} Current working directory of the child process
446   * `stdio` {Array|String} Child's stdio configuration. (See above)
447     Only stdin is configurable, anything else will lead to unpredictable
448     results.
449   * `customFds` {Array} **Deprecated** File descriptors for the child to use
450     for stdio.  (See above)
451   * `env` {Object} Environment key-value pairs
452   * `encoding` {String} (Default: 'utf8')
453   * `timeout` {Number} (Default: 0)
454   * `maxBuffer` {Number} (Default: 200*1024)
455   * `killSignal` {String} (Default: 'SIGTERM')
456 * `callback` {Function} called with the output when process terminates
457   * `error` {Error}
458   * `stdout` {Buffer}
459   * `stderr` {Buffer}
460 * Return: ChildProcess object
461
462 Runs a command in a shell and buffers the output.
463
464     var exec = require('child_process').exec,
465         child;
466
467     child = exec('cat *.js bad_file | wc -l',
468       function (error, stdout, stderr) {
469         console.log('stdout: ' + stdout);
470         console.log('stderr: ' + stderr);
471         if (error !== null) {
472           console.log('exec error: ' + error);
473         }
474     });
475
476 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
477 will be `null`.  On error, `error` will be an instance of `Error` and `err.code`
478 will be the exit code of the child process, and `err.signal` will be set to the
479 signal that terminated the process.
480
481 There is a second optional argument to specify several options. The
482 default options are
483
484     { encoding: 'utf8',
485       timeout: 0,
486       maxBuffer: 200*1024,
487       killSignal: 'SIGTERM',
488       cwd: null,
489       env: null }
490
491 If `timeout` is greater than 0, then it will kill the child process
492 if it runs longer than `timeout` milliseconds. The child process is killed with
493 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
494 amount of data allowed on stdout or stderr - if this value is exceeded then
495 the child process is killed.
496
497
498 ## child_process.execFile(file, args, options, callback)
499
500 * `file` {String} The filename of the program to run
501 * `args` {Array} List of string arguments
502 * `options` {Object}
503   * `cwd` {String} Current working directory of the child process
504   * `stdio` {Array|String} Child's stdio configuration. (See above)
505   * `customFds` {Array} **Deprecated** File descriptors for the child to use
506     for stdio.  (See above)
507   * `env` {Object} Environment key-value pairs
508   * `encoding` {String} (Default: 'utf8')
509   * `timeout` {Number} (Default: 0)
510   * `maxBuffer` {Number} (Default: 200\*1024)
511   * `killSignal` {String} (Default: 'SIGTERM')
512 * `callback` {Function} called with the output when process terminates
513   * `error` {Error}
514   * `stdout` {Buffer}
515   * `stderr` {Buffer}
516 * Return: ChildProcess object
517
518 This is similar to `child_process.exec()` except it does not execute a
519 subshell but rather the specified file directly. This makes it slightly
520 leaner than `child_process.exec`. It has the same options.
521
522
523 ## child\_process.fork(modulePath, [args], [options])
524
525 * `modulePath` {String} The module to run in the child
526 * `args` {Array} List of string arguments
527 * `options` {Object}
528   * `cwd` {String} Current working directory of the child process
529   * `env` {Object} Environment key-value pairs
530   * `encoding` {String} (Default: 'utf8')
531   * `execPath` {String} Executable used to create the child process
532 * Return: ChildProcess object
533
534 This is a special case of the `spawn()` functionality for spawning Node
535 processes. In addition to having all the methods in a normal ChildProcess
536 instance, the returned object has a communication channel built-in. See
537 `child.send(message, [sendHandle])` for details.
538
539 By default the spawned Node process will have the stdout, stderr associated
540 with the parent's. To change this behavior set the `silent` property in the
541 `options` object to `true`.
542
543 The child process does not automatically exit once it's done, you need to call
544 `process.exit()` explicitly. This limitation may be lifted in the future.
545
546 These child Nodes are still whole new instances of V8. Assume at least 30ms
547 startup and 10mb memory for each new Node. That is, you cannot create many
548 thousands of them.
549
550 The `execPath` property in the `options` object allows for a process to be
551 created for the child rather than the current `node` executable. This should be
552 done with care and by default will talk over the fd represented an
553 environmental variable `NODE_CHANNEL_FD` on the child process. The input and
554 output on this fd is expected to be line delimited JSON objects.
555
556 [EventEmitter]: events.html#events_class_events_eventemitter