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