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