doc: fix callback argument of child_process.exec, execFile
[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 See `waitpid(2)`.
39
40 ### child.stdin
41
42 * {Stream object}
43
44 A `Writable Stream` that represents the child process's `stdin`.
45 Closing this stream via `end()` often causes the child process to terminate.
46
47 If the child stdio streams are shared with the parent, then this will
48 not be set.
49
50 ### child.stdout
51
52 * {Stream object}
53
54 A `Readable Stream` that represents the child process's `stdout`.
55
56 If the child stdio streams are shared with the parent, then this will
57 not be set.
58
59 ### child.stderr
60
61 * {Stream object}
62
63 A `Readable Stream` that represents the child process's `stderr`.
64
65 If the child stdio streams are shared with the parent, then this will
66 not be set.
67
68 ### child.pid
69
70 * {Integer}
71
72 The PID of the child process.
73
74 Example:
75
76     var spawn = require('child_process').spawn,
77         grep  = spawn('grep', ['ssh']);
78
79     console.log('Spawned child pid: ' + grep.pid);
80     grep.stdin.end();
81
82 ### child.kill([signal])
83
84 * `signal` {String}
85
86 Send a signal to the child process. If no argument is given, the process will
87 be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
88
89     var spawn = require('child_process').spawn,
90         grep  = spawn('grep', ['ssh']);
91
92     grep.on('exit', function (code, signal) {
93       console.log('child process terminated due to receipt of signal '+signal);
94     });
95
96     // send SIGHUP to process
97     grep.kill('SIGHUP');
98
99 Note that while the function is called `kill`, the signal delivered to the child
100 process may not actually kill it.  `kill` really just sends a signal to a process.
101
102 See `kill(2)`
103
104 ### child.send(message, [sendHandle])
105
106 * `message` {Object}
107 * `sendHandle` {Handle object}
108
109 Send a message (and, optionally, a handle object) to a child process.
110
111 See `child_process.fork()` for details.
112
113 ## child_process.spawn(command, [args], [options])
114
115 * `command` {String} The command to run
116 * `args` {Array} List of string arguments
117 * `options` {Object}
118   * `cwd` {String} Current working directory of the child process
119   * `customFds` {Array} **Deprecated** File descriptors for the child to use
120     for stdio.  (See below)
121   * `env` {Object} Environment key-value pairs
122   * `setsid` {Boolean}
123 * return: {ChildProcess object}
124
125 Launches a new process with the given `command`, with  command line arguments in `args`.
126 If omitted, `args` defaults to an empty Array.
127
128 The third argument is used to specify additional options, which defaults to:
129
130     { cwd: undefined,
131       env: process.env
132     }
133
134 `cwd` allows you to specify the working directory from which the process is spawned.
135 Use `env` to specify environment variables that will be visible to the new process.
136
137 Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
138
139     var util  = require('util'),
140         spawn = require('child_process').spawn,
141         ls    = spawn('ls', ['-lh', '/usr']);
142
143     ls.stdout.on('data', function (data) {
144       console.log('stdout: ' + data);
145     });
146
147     ls.stderr.on('data', function (data) {
148       console.log('stderr: ' + data);
149     });
150
151     ls.on('exit', function (code) {
152       console.log('child process exited with code ' + code);
153     });
154
155
156 Example: A very elaborate way to run 'ps ax | grep ssh'
157
158     var util  = require('util'),
159         spawn = require('child_process').spawn,
160         ps    = spawn('ps', ['ax']),
161         grep  = spawn('grep', ['ssh']);
162
163     ps.stdout.on('data', function (data) {
164       grep.stdin.write(data);
165     });
166
167     ps.stderr.on('data', function (data) {
168       console.log('ps stderr: ' + data);
169     });
170
171     ps.on('exit', function (code) {
172       if (code !== 0) {
173         console.log('ps process exited with code ' + code);
174       }
175       grep.stdin.end();
176     });
177
178     grep.stdout.on('data', function (data) {
179       console.log(data);
180     });
181
182     grep.stderr.on('data', function (data) {
183       console.log('grep stderr: ' + data);
184     });
185
186     grep.on('exit', function (code) {
187       if (code !== 0) {
188         console.log('grep process exited with code ' + code);
189       }
190     });
191
192
193 Example of checking for failed exec:
194
195     var spawn = require('child_process').spawn,
196         child = spawn('bad_command');
197
198     child.stderr.setEncoding('utf8');
199     child.stderr.on('data', function (data) {
200       if (/^execvp\(\)/.test(data)) {
201         console.log('Failed to start child process.');
202       }
203     });
204
205 Note that if spawn receives an empty options object, it will result in
206 spawning the process with an empty environment rather than using
207 `process.env`. This due to backwards compatibility issues with a deprecated
208 API.
209
210 There is a deprecated option called `customFds` which allows one to specify
211 specific file descriptors for the stdio of the child process. This API was
212 not portable to all platforms and therefore removed.
213 With `customFds` it was possible to hook up the new process' `[stdin, stdout,
214 stderr]` to existing streams; `-1` meant that a new stream should be created.
215 Use at your own risk.
216
217 There are several internal options. In particular `stdinStream`,
218 `stdoutStream`, `stderrStream`. They are for INTERNAL USE ONLY. As with all
219 undocumented APIs in Node, they should not be used.
220
221 See also: `child_process.exec()` and `child_process.fork()`
222
223 ## child_process.exec(command, [options], callback)
224
225 * `command` {String} The command to run, with space-separated arguments
226 * `options` {Object}
227   * `cwd` {String} Current working directory of the child process
228   * `customFds` {Array} **Deprecated** File descriptors for the child to use
229     for stdio.  (See below)
230   * `env` {Object} Environment key-value pairs
231   * `setsid` {Boolean}
232   * `encoding` {String} (Default: 'utf8')
233   * `timeout` {Number} (Default: 0)
234   * `maxBuffer` {Number} (Default: 200*1024)
235   * `killSignal` {String} (Default: 'SIGTERM')
236 * `callback` {Function} called with the output when process terminates
237   * `error` {Error}
238   * `stdout` {Buffer}
239   * `stderr` {Buffer}
240 * Return: ChildProcess object
241
242 Runs a command in a shell and buffers the output.
243
244     var util = require('util'),
245         exec = require('child_process').exec,
246         child;
247
248     child = exec('cat *.js bad_file | wc -l',
249       function (error, stdout, stderr) {
250         console.log('stdout: ' + stdout);
251         console.log('stderr: ' + stderr);
252         if (error !== null) {
253           console.log('exec error: ' + error);
254         }
255     });
256
257 The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
258 will be `null`.  On error, `error` will be an instance of `Error` and `err.code`
259 will be the exit code of the child process, and `err.signal` will be set to the
260 signal that terminated the process.
261
262 There is a second optional argument to specify several options. The
263 default options are
264
265     { encoding: 'utf8',
266       timeout: 0,
267       maxBuffer: 200*1024,
268       killSignal: 'SIGTERM',
269       cwd: null,
270       env: null }
271
272 If `timeout` is greater than 0, then it will kill the child process
273 if it runs longer than `timeout` milliseconds. The child process is killed with
274 `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
275 amount of data allowed on stdout or stderr - if this value is exceeded then
276 the child process is killed.
277
278
279 ## child_process.execFile(file, args, options, callback)
280
281 * `file` {String} The filename of the program to run
282 * `args` {Array} List of string arguments
283 * `options` {Object}
284   * `cwd` {String} Current working directory of the child process
285   * `customFds` {Array} **Deprecated** File descriptors for the child to use
286     for stdio.  (See below)
287   * `env` {Object} Environment key-value pairs
288   * `setsid` {Boolean}
289   * `encoding` {String} (Default: 'utf8')
290   * `timeout` {Number} (Default: 0)
291   * `maxBuffer` {Number} (Default: 200*1024)
292   * `killSignal` {String} (Default: 'SIGTERM')
293 * `callback` {Function} called with the output when process terminates
294   * `error` {Error}
295   * `stdout` {Buffer}
296   * `stderr` {Buffer}
297 * Return: ChildProcess object
298
299 This is similar to `child_process.exec()` except it does not execute a
300 subshell but rather the specified file directly. This makes it slightly
301 leaner than `child_process.exec`. It has the same options.
302
303
304 ## child_process.fork(modulePath, [args], [options])
305
306 * `modulePath` {String} The module to run in the child
307 * `args` {Array} List of string arguments
308 * `options` {Object}
309   * `cwd` {String} Current working directory of the child process
310   * `customFds` {Array} **Deprecated** File descriptors for the child to use
311     for stdio.  (See below)
312   * `env` {Object} Environment key-value pairs
313   * `setsid` {Boolean}
314   * `encoding` {String} (Default: 'utf8')
315   * `timeout` {Number} (Default: 0)
316 * Return: ChildProcess object
317
318 This is a special case of the `spawn()` functionality for spawning Node
319 processes. In addition to having all the methods in a normal ChildProcess
320 instance, the returned object has a communication channel built-in. The
321 channel is written to with `child.send(message, [sendHandle])` and messages
322 are received by a `'message'` event on the child.
323
324 For example:
325
326     var cp = require('child_process');
327
328     var n = cp.fork(__dirname + '/sub.js');
329
330     n.on('message', function(m) {
331       console.log('PARENT got message:', m);
332     });
333
334     n.send({ hello: 'world' });
335
336 And then the child script, `'sub.js'` might look like this:
337
338     process.on('message', function(m) {
339       console.log('CHILD got message:', m);
340     });
341
342     process.send({ foo: 'bar' });
343
344 In the child the `process` object will have a `send()` method, and `process`
345 will emit objects each time it receives a message on its channel.
346
347 By default the spawned Node process will have the stdin, stdout, stderr
348 associated with the parent's.
349
350 These child Nodes are still whole new instances of V8. Assume at least 30ms
351 startup and 10mb memory for each new Node. That is, you cannot create many
352 thousands of them.
353
354 The `sendHandle` option to `child.send()` is for sending a handle object to
355 another process. Child will receive the handle as as second argument to the
356 `message` event. Here is an example of sending a handle:
357
358     var server = require('net').createServer();
359     var child = require('child_process').fork(__dirname + '/child.js');
360     // Open up the server object and send the handle.
361     server.listen(1337, function() {
362       child.send({ server: true }, server._handle);
363     });
364
365 Here is an example of receiving the server handle and sharing it between
366 processes:
367
368     process.on('message', function(m, serverHandle) {
369       if (serverHandle) {
370         var server = require('net').createServer();
371         server.listen(serverHandle);
372       }
373     });
374
375
376