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