child_process: allow sending a net Socket and Server object using child.send
[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 some connections will be handled by the parent and some by the child.
196
197 **send socket object**
198
199 Here is an example of sending a socket. It will spawn two childs and handle
200 connections with the remote address `74.125.127.100` as VIP by sending the
201 socket to a "special" child process. Other sockets will go to a "normal" process.
202
203     var normal = require('child_process').fork('child.js', ['normal']);
204     var special = require('child_process').fork('child.js', ['special']);
205
206     // Open up the server and send sockets to child
207     var server = require('net').createServer();
208     server.on('connection', function (socket) {
209
210       // if this is a VIP
211       if (socket.remoteAddress === '74.125.127.100') {
212         special.send('socket', socket);
213         return;
214       }
215       // just the usual dudes
216       normal.send('socket', socket);
217     });
218     server.listen(1337);
219
220 The `child.js` could look like this:
221
222     process.on('message', function(m, socket) {
223       if (m === 'socket') {
224         socket.end('You where handled as a ' + process.argv[2] + ' person');
225       }
226     });
227
228 Note that once a single socket has been sent to a child the parent can no
229 longer keep track of when the socket is destroyed. To indicate this condition
230 the `.connections` property becomes `null`.
231 It is also recomended not to use `.maxConnections` in this condition.
232
233 ### child.disconnect()
234
235 To close the IPC connection between parent and child use the
236 `child.disconnect()` method. This allows the child to exit gracefully since
237 there is no IPC channel keeping it alive. When calling this method the
238 `disconnect` event will be emitted in both parent and child, and the
239 `connected` flag will be set to `false`. Please note that you can also call
240 `process.disconnect()` in the child process.
241
242 ## child_process.spawn(command, [args], [options])
243
244 * `command` {String} The command to run
245 * `args` {Array} List of string arguments
246 * `options` {Object}
247   * `cwd` {String} Current working directory of the child process
248   * `customFds` {Array} **Deprecated** File descriptors for the child to use
249     for stdio.  (See below)
250   * `env` {Object} Environment key-value pairs
251   * `setsid` {Boolean}
252 * return: {ChildProcess object}
253
254 Launches a new process with the given `command`, with  command line arguments in `args`.
255 If omitted, `args` defaults to an empty Array.
256
257 The third argument is used to specify additional options, which defaults to:
258
259     { cwd: undefined,
260       env: process.env
261     }
262
263 `cwd` allows you to specify the working directory from which the process is spawned.
264 Use `env` to specify environment variables that will be visible to the new process.
265
266 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
267
268     var util  = require('util'),
269         spawn = require('child_process').spawn,
270         ls    = spawn('ls', ['-lh', '/usr']);
271
272     ls.stdout.on('data', function (data) {
273       console.log('stdout: ' + data);
274     });
275
276     ls.stderr.on('data', function (data) {
277       console.log('stderr: ' + data);
278     });
279
280     ls.on('exit', function (code) {
281       console.log('child process exited with code ' + code);
282     });
283
284
285 Example: A very elaborate way to run 'ps ax | grep ssh'
286
287     var util  = require('util'),
288         spawn = require('child_process').spawn,
289         ps    = spawn('ps', ['ax']),
290         grep  = spawn('grep', ['ssh']);
291
292     ps.stdout.on('data', function (data) {
293       grep.stdin.write(data);
294     });
295
296     ps.stderr.on('data', function (data) {
297       console.log('ps stderr: ' + data);
298     });
299
300     ps.on('exit', function (code) {
301       if (code !== 0) {
302         console.log('ps process exited with code ' + code);
303       }
304       grep.stdin.end();
305     });
306
307     grep.stdout.on('data', function (data) {
308       console.log(data);
309     });
310
311     grep.stderr.on('data', function (data) {
312       console.log('grep stderr: ' + data);
313     });
314
315     grep.on('exit', function (code) {
316       if (code !== 0) {
317         console.log('grep process exited with code ' + code);
318       }
319     });
320
321
322 Example of checking for failed exec:
323
324     var spawn = require('child_process').spawn,
325         child = spawn('bad_command');
326
327     child.stderr.setEncoding('utf8');
328     child.stderr.on('data', function (data) {
329       if (/^execvp\(\)/.test(data)) {
330         console.log('Failed to start child process.');
331       }
332     });
333
334 Note that if spawn receives an empty options object, it will result in
335 spawning the process with an empty environment rather than using
336 `process.env`. This due to backwards compatibility issues with a deprecated
337 API.
338
339 There is a deprecated option called `customFds` which allows one to specify
340 specific file descriptors for the stdio of the child process. This API was
341 not portable to all platforms and therefore removed.
342 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
343 stderr]` to existing streams; `-1` meant that a new stream should be created.
344 Use at your own risk.
345
346 There are several internal options. In particular `stdinStream`,
347 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
348 undocumented APIs in Node, they should not be used.
349
350 See also: `child_process.exec()` and `child_process.fork()`
351
352 ## child_process.exec(command, [options], callback)
353
354 * `command` {String} The command to run, with space-separated arguments
355 * `options` {Object}
356   * `cwd` {String} Current working directory of the child process
357   * `customFds` {Array} **Deprecated** File descriptors for the child to use
358     for stdio.  (See below)
359   * `env` {Object} Environment key-value pairs
360   * `setsid` {Boolean}
361   * `encoding` {String} (Default: 'utf8')
362   * `timeout` {Number} (Default: 0)
363   * `maxBuffer` {Number} (Default: 200*1024)
364   * `killSignal` {String} (Default: 'SIGTERM')
365 * `callback` {Function} called with the output when process terminates
366   * `error` {Error}
367   * `stdout` {Buffer}
368   * `stderr` {Buffer}
369 * Return: ChildProcess object
370
371 Runs a command in a shell and buffers the output.
372
373     var util = require('util'),
374         exec = require('child_process').exec,
375         child;
376
377     child = exec('cat *.js bad_file | wc -l',
378       function (error, stdout, stderr) {
379         console.log('stdout: ' + stdout);
380         console.log('stderr: ' + stderr);
381         if (error !== null) {
382           console.log('exec error: ' + error);
383         }
384     });
385
386 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
387 will be `null`.  On error, `error` will be an instance of `Error` and `err.code`
388 will be the exit code of the child process, and `err.signal` will be set to the
389 signal that terminated the process.
390
391 There is a second optional argument to specify several options. The
392 default options are
393
394     { encoding: 'utf8',
395       timeout: 0,
396       maxBuffer: 200*1024,
397       killSignal: 'SIGTERM',
398       cwd: null,
399       env: null }
400
401 If `timeout` is greater than 0, then it will kill the child process
402 if it runs longer than `timeout` milliseconds. The child process is killed with
403 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
404 amount of data allowed on stdout or stderr - if this value is exceeded then
405 the child process is killed.
406
407
408 ## child_process.execFile(file, args, options, callback)
409
410 * `file` {String} The filename of the program to run
411 * `args` {Array} List of string arguments
412 * `options` {Object}
413   * `cwd` {String} Current working directory of the child process
414   * `customFds` {Array} **Deprecated** File descriptors for the child to use
415     for stdio.  (See below)
416   * `env` {Object} Environment key-value pairs
417   * `setsid` {Boolean}
418   * `encoding` {String} (Default: 'utf8')
419   * `timeout` {Number} (Default: 0)
420   * `maxBuffer` {Number} (Default: 200*1024)
421   * `killSignal` {String} (Default: 'SIGTERM')
422 * `callback` {Function} called with the output when process terminates
423   * `error` {Error}
424   * `stdout` {Buffer}
425   * `stderr` {Buffer}
426 * Return: ChildProcess object
427
428 This is similar to `child_process.exec()` except it does not execute a
429 subshell but rather the specified file directly. This makes it slightly
430 leaner than `child_process.exec`. It has the same options.
431
432
433 ## child_process.fork(modulePath, [args], [options])
434
435 * `modulePath` {String} The module to run in the child
436 * `args` {Array} List of string arguments
437 * `options` {Object}
438   * `cwd` {String} Current working directory of the child process
439   * `customFds` {Array} **Deprecated** File descriptors for the child to use
440     for stdio.  (See below)
441   * `env` {Object} Environment key-value pairs
442   * `setsid` {Boolean}
443   * `encoding` {String} (Default: 'utf8')
444   * `timeout` {Number} (Default: 0)
445 * Return: ChildProcess object
446
447 This is a special case of the `spawn()` functionality for spawning Node
448 processes. In addition to having all the methods in a normal ChildProcess
449 instance, the returned object has a communication channel built-in. See
450 `child.send(message, [sendHandle])` for details.
451
452 By default the spawned Node process will have the stdout, stderr associated
453 with the parent's. To change this behavior set the `silent` property in the
454 `options` object to `true`.
455
456 These child Nodes are still whole new instances of V8. Assume at least 30ms
457 startup and 10mb memory for each new Node. That is, you cannot create many
458 thousands of them.