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