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