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