Skip to content

Commit c1bc9a1

Browse files
jasnellFishrock123
authored andcommittedJan 6, 2016
doc: improve child_process.markdown copy
General improvements to child_process.markdown PR-URL: #4383 Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
1 parent ffb4a6e commit c1bc9a1

File tree

1 file changed

+565
-410
lines changed

1 file changed

+565
-410
lines changed
 

‎doc/api/child_process.markdown

+565-410
Original file line numberDiff line numberDiff line change
@@ -2,358 +2,113 @@
22

33
Stability: 2 - Stable
44

5-
Node.js 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 may not be 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 as explained [below][].
16-
17-
For scripting purposes you may find the [synchronous counterparts][] more
18-
convenient.
19-
20-
## Class: ChildProcess
21-
22-
`ChildProcess` is an [`EventEmitter`][].
23-
24-
Child processes always have three streams associated with them. `child.stdin`,
25-
`child.stdout`, and `child.stderr`. These may be shared with the stdio
26-
streams of the parent process, or they may be separate stream objects
27-
which can be piped to and from.
28-
29-
The `ChildProcess` class is not intended to be used directly. Use the
30-
[`spawn()`][], [`exec()`][], [`execFile()`][], or [`fork()`][] methods to create
31-
an instance of `ChildProcess`.
32-
33-
### Event: 'close'
34-
35-
* `code` {Number} the exit code, if it exited normally.
36-
* `signal` {String} the signal passed to kill the child process, if it
37-
was killed by the parent.
38-
39-
This event is emitted when the stdio streams of a child process have all
40-
terminated. This is distinct from `'exit'`, since multiple processes
41-
might share the same stdio streams.
42-
43-
### Event: 'disconnect'
44-
45-
This event is emitted after calling the `.disconnect()` method in the parent
46-
or in the child. After disconnecting it is no longer possible to send messages,
47-
and the `.connected` property is false.
48-
49-
### Event: 'error'
50-
51-
* `err` {Error Object} the error.
52-
53-
Emitted when:
54-
55-
1. The process could not be spawned, or
56-
2. The process could not be killed, or
57-
3. Sending a message to the child process failed.
58-
59-
Note that the `'exit'` event may or may not fire after an error has occurred.
60-
If you are listening on both events to fire a function, remember to guard
61-
against calling your function twice.
62-
63-
See also [`ChildProcess#kill()`][] and [`ChildProcess#send()`][].
64-
65-
### Event: 'exit'
66-
67-
* `code` {Number} the exit code, if it exited normally.
68-
* `signal` {String} the signal passed to kill the child process, if it
69-
was killed by the parent.
70-
71-
This event is emitted after the child process ends. If the process terminated
72-
normally, `code` is the final exit code of the process, otherwise `null`. If
73-
the process terminated due to receipt of a signal, `signal` is the string name
74-
of the signal, otherwise `null`.
75-
76-
Note that the child process stdio streams might still be open.
77-
78-
Also, note that Node.js establishes signal handlers for `SIGINT` and
79-
`SIGTERM`. It will not terminate due to receipt of those signals. It will exit.
80-
81-
See `waitpid(2)`.
82-
83-
### Event: 'message'
84-
85-
* `message` {Object} a parsed JSON object or primitive value.
86-
* `sendHandle` {Handle object} a [`net.Socket`][] or [`net.Server`][] object, or
87-
undefined.
88-
89-
Messages sent by `.send(message, [sendHandle])` are obtained using the
90-
`'message'` event.
91-
92-
### child.connected
93-
94-
* {Boolean} Set to false after `.disconnect` is called
95-
96-
If `.connected` is false, it is no longer possible to send messages.
97-
98-
### child.disconnect()
99-
100-
Close the IPC channel between parent and child, allowing the child to exit
101-
gracefully once there are no other connections keeping it alive. After calling
102-
this method the `.connected` flag will be set to `false` in both the parent and
103-
child, and it is no longer possible to send messages.
104-
105-
The `'disconnect'` event will be emitted when there are no messages in the
106-
process of being received, most likely immediately.
107-
108-
Note that you can also call `process.disconnect()` in the child process when the
109-
child process has any open IPC channels with the parent (i.e [`fork()`][]).
110-
111-
### child.kill([signal])
112-
113-
* `signal` {String}
114-
115-
Send a signal to the child process. If no argument is given, the process will
116-
be sent `'SIGTERM'`. See `signal(7)` for a list of available signals.
5+
The `child_process` module provides the ability to spawn child processes in
6+
a manner that is similar, but not identical, to [`popen(3)`][]. This capability
7+
is primarily provided by the `child_process.spawn()` function:
1178

1189
const spawn = require('child_process').spawn;
119-
const grep = spawn('grep', ['ssh']);
10+
const ls = spawn('ls', ['-lh', '/usr']);
12011

121-
grep.on('close', (code, signal) => {
122-
console.log(
123-
`child process terminated due to receipt of signal ${signal}`);
12+
ls.stdout.on('data', (data) => {
13+
console.log(`stdout: ${data}`);
12414
});
12515

126-
// send SIGHUP to process
127-
grep.kill('SIGHUP');
128-
129-
May emit an `'error'` event when the signal cannot be delivered. Sending a
130-
signal to a child process that has already exited is not an error but may
131-
have unforeseen consequences. Specifically, if the process identifier (PID) has
132-
been reassigned to another process, the signal will be delivered to that
133-
process instead. What happens next is anyone's guess.
134-
135-
Note that while the function is called `kill`, the signal delivered to the
136-
child process may not actually kill it. `kill` really just sends a signal
137-
to a process.
138-
139-
See `kill(2)`
140-
141-
### child.pid
142-
143-
* {Integer}
144-
145-
The process identifier (PID) of the child process.
146-
147-
Example:
148-
149-
const spawn = require('child_process').spawn;
150-
const grep = spawn('grep', ['ssh']);
151-
152-
console.log(`Spawned child pid: ${grep.pid}`);
153-
grep.stdin.end();
154-
155-
### child.send(message[, sendHandle][, callback])
156-
157-
* `message` {Object}
158-
* `sendHandle` {Handle object}
159-
* `callback` {Function}
160-
* Return: Boolean
161-
162-
When using [`child_process.fork()`][] you can write to the child using
163-
`child.send(message[, sendHandle][, callback])` and messages are received by
164-
a `'message'` event on the child.
165-
166-
For example:
167-
168-
const cp = require('child_process');
169-
const n = cp.fork(`${__dirname}/sub.js`);
170-
171-
n.on('message', (m) => {
172-
console.log('PARENT got message:', m);
16+
ls.stderr.on('data', (data) => {
17+
console.log(`stderr: ${data}`);
17318
});
17419

175-
n.send({ hello: 'world' });
176-
177-
And then the child script, `'sub.js'` might look like this:
178-
179-
process.on('message', (m) => {
180-
console.log('CHILD got message:', m);
20+
ls.on('close', (code) => {
21+
console.log(`child process exited with code ${code}`);
18122
});
18223

183-
process.send({ foo: 'bar' });
184-
185-
In the child, the `process` object will have a `send()` method, and `process`
186-
will emit objects each time it receives a message on its channel.
24+
By default, pipes for `stdin`, `stdout` and `stderr` are established between
25+
the parent Node.js process and the spawned child. It is possible to stream data
26+
through these pipes in a non-blocking way. *Note, however, that some programs
27+
use line-buffered I/O internally. While that does not affect Node.js, it can
28+
mean that data sent to the child process may not be immediately consumed.*
29+
30+
The `child_process.spawn()` method spawns the child process asynchronously,
31+
without blocking the Node.js event loop. The `child_process.spawnSync()`
32+
function provides equivalent functionality in a synchronous manner that blocks
33+
the event loop until the spawned process either exits of is terminated.
34+
35+
For convenience, the `child_process` module provides a handful of synchronous
36+
and asynchronous alternatives to `child_process.spawn()` and
37+
`child_process.spawnSync()`, each of which are documented fully [below][].
38+
*Note that each of these alternatives are implemented on top of
39+
`child_process.spawn()` or `child_process.spawnSync()`.*
40+
41+
* `child_process.exec()`: spawns a shell and runs a command within that shell,
42+
passing the `stdout` and `stderr` to a callback function when complete.
43+
* `child_process.execFile()`: similar to `child_process.exec()` except that
44+
it spawns the command directly without first spawning a shell.
45+
* `child_process.fork()`: spawns a new Node.js process and invokes a
46+
specified module with an IPC communication channel established that allows
47+
sending messages between parent and child.
48+
* `child_process.execSync()`: a synchronous version of
49+
`child_process.exec()` that *will* block the Node.js event loop.
50+
* `child_process.execFileSync()`: a synchronous version of
51+
`child_process.execFile()` that *will* block the Node.js event loop.
52+
53+
For certain use cases, such as automating shell scripts, the
54+
[synchronous counterparts][] may be more convenient. In many cases, however,
55+
the synchronous methods can have significant impact on performance due to
56+
stalling the event loop while spawned processes complete.
18757

188-
There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
189-
containing a `NODE_` prefix in its `cmd` property will not be emitted in
190-
the `'message'` event, since they are internal messages used by Node.js core.
191-
Messages containing the prefix are emitted in the `'internalMessage'` event.
192-
Avoid using this feature; it is subject to change without notice.
193-
194-
The `sendHandle` option to `child.send()` is for sending a TCP server or
195-
socket object to another process. The child will receive the object as its
196-
second argument to the `'message'` event.
58+
## Asynchronous Process Creation
19759

198-
The `callback` option is a function that is invoked after the message is
199-
sent but before the target may have received it. It is called with a single
200-
argument: `null` on success, or an [`Error`][] object on failure.
60+
The `child_process.spawn()`, `child_process.fork()`, `child_process.exec()`,
61+
and `child_process.execFile()` methods all follow the idiomatic asynchronous
62+
programming pattern typical of other Node.js APIs.
20163

202-
`child.send()` emits an `'error'` event if no callback was given and the message
203-
cannot be sent, for example because the child process has already exited.
64+
Each of the methods returns a [ChildProcess][] instance. These objects
65+
implement the Node.js [EventEmitter][] API, allowing the parent process to
66+
register listener functions that are called when certain events occur during
67+
the life cycle of the child process.
20468

205-
`child.send()` returns `false` if the channel has closed or when the backlog of
206-
unsent messages exceeds a threshold that makes it unwise to send more.
207-
Otherwise, it returns `true`. Use the callback mechanism to implement flow
208-
control.
69+
The `child_process.exec()` and `child_process.execFile()` methods additionally
70+
allow for an optional `callback` function to be specified that is invoked
71+
when the child process terminates.
20972

210-
#### Example: sending server object
73+
### Spawning `.bat` and `.cmd` files on Windows
21174

212-
Here is an example of sending a server:
75+
The importance of the distinction between `child_process.exec()` and
76+
`child_process.execFile()` can vary based on platform. On Unix-type operating
77+
systems (Unix, Linux, OSX) `child_process.execFile()` can be more efficient
78+
because it does not spawn a shell. On Windows, however, `.bat` and `.cmd`
79+
files are not executable on their own without a terminal and therefore cannot
80+
be launched using `child_process.execFile()` (or even `child_process.spawn()`).
81+
When running on Windows, `.bat` and `.cmd` files can only be invoked using
82+
either `child_process.exec()` or by spawning `cmd.exe` and passing the `.bat`
83+
or `.cmd` file as an argument (which is what `child_process.exec()` does).
21384

214-
const child = require('child_process').fork('child.js');
85+
// On Windows Only ...
86+
const spawn = require('child_process').spawn;
87+
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
21588

216-
// Open up the server object and send the handle.
217-
const server = require('net').createServer();
218-
server.on('connection', (socket) => {
219-
socket.end('handled by parent');
220-
});
221-
server.listen(1337, () => {
222-
child.send('server', server);
89+
bat.stdout.on('data', (data) => {
90+
console.log(data);
22391
});
22492

225-
And the child would then receive the server object as:
226-
227-
process.on('message', (m, server) => {
228-
if (m === 'server') {
229-
server.on('connection', (socket) => {
230-
socket.end('handled by child');
231-
});
232-
}
93+
bat.stderr.on('data', (data) => {
94+
console.log(data);
23395
});
23496

235-
Note that the server is now shared between the parent and child, this means
236-
that some connections will be handled by the parent and some by the child.
237-
238-
For `dgram` servers the workflow is exactly the same. Here you listen on
239-
a `'message'` event instead of `'connection'` and use `server.bind` instead of
240-
`server.listen`. (Currently only supported on UNIX platforms.)
241-
242-
#### Example: sending socket object
243-
244-
Here is an example of sending a socket. It will spawn two children and handle
245-
connections with the remote address `74.125.127.100` as VIP by sending the
246-
socket to a "special" child process. Other sockets will go to a "normal"
247-
process.
248-
249-
const normal = require('child_process').fork('child.js', ['normal']);
250-
const special = require('child_process').fork('child.js', ['special']);
251-
252-
// Open up the server and send sockets to child
253-
const server = require('net').createServer();
254-
server.on('connection', (socket) => {
255-
256-
// if this is a VIP
257-
if (socket.remoteAddress === '74.125.127.100') {
258-
special.send('socket', socket);
259-
return;
260-
}
261-
// just the usual...
262-
normal.send('socket', socket);
97+
bat.on('exit', (code) => {
98+
console.log(`Child exited with code ${code}`);
26399
});
264-
server.listen(1337);
265-
266-
The `child.js` could look like this:
267100

268-
process.on('message', (m, socket) => {
269-
if (m === 'socket') {
270-
socket.end(`You were handled as a ${process.argv[2]} person`);
101+
// OR...
102+
const exec = require('child_process').exec;
103+
exec('my.bat', (err, stdout, stderr) => {
104+
if (err) {
105+
console.error(err);
106+
return;
271107
}
108+
console.log(stdout);
272109
});
273110

274-
Note that once a single socket has been sent to a child the parent can no
275-
longer keep track of when the socket is destroyed. To indicate this condition
276-
the `.connections` property becomes `null`.
277-
It is also recommended not to use `.maxConnections` in this condition.
278-
279-
### child.stderr
280-
281-
* {Stream object}
282-
283-
A `Readable Stream` that represents the child process's `stderr`.
284-
285-
If the child was not spawned with `stdio[2]` set to `'pipe'`, then this will
286-
not be set.
287-
288-
`child.stderr` is shorthand for `child.stdio[2]`. Both properties will refer
289-
to the same object, or null.
290-
291-
### child.stdin
292-
293-
* {Stream object}
294-
295-
A `Writable Stream` that represents the child process's `stdin`.
296-
If the child is waiting to read all its input, it will not continue until this
297-
stream has been closed via `end()`.
298-
299-
If the child was not spawned with `stdio[0]` set to `'pipe'`, then this will
300-
not be set.
301-
302-
`child.stdin` is shorthand for `child.stdio[0]`. Both properties will refer
303-
to the same object, or null.
304-
305-
### child.stdio
306-
307-
* {Array}
308-
309-
A sparse array of pipes to the child process, corresponding with positions in
310-
the [`stdio`][] option to [`spawn()`][] that have been set to `'pipe'`.
311-
Note that streams 0-2 are also available as ChildProcess.stdin,
312-
ChildProcess.stdout, and ChildProcess.stderr, respectively.
313-
314-
In the following example, only the child's fd `1` is setup as a pipe, so only
315-
the parent's `child.stdio[1]` is a stream, all other values in the array are
316-
`null`.
317-
318-
const assert = require('assert');
319-
const fs = require('fs');
320-
const child_process = require('child_process');
321-
322-
const child = child_process.spawn('ls', {
323-
stdio: [
324-
0, // use parents stdin for child
325-
'pipe', // pipe child's stdout to parent
326-
fs.openSync('err.out', 'w') // direct child's stderr to a file
327-
]
328-
});
329-
330-
assert.equal(child.stdio[0], null);
331-
assert.equal(child.stdio[0], child.stdin);
332-
333-
assert(child.stdout);
334-
assert.equal(child.stdio[1], child.stdout);
335-
336-
assert.equal(child.stdio[2], null);
337-
assert.equal(child.stdio[2], child.stderr);
338-
339-
### child.stdout
340-
341-
* {Stream object}
342-
343-
A `Readable Stream` that represents the child process's `stdout`.
344-
345-
If the child was not spawned with `stdio[1]` set to `'pipe'`, then this will
346-
not be set.
347-
348-
`child.stdout` is shorthand for `child.stdio[1]`. Both properties will refer
349-
to the same object, or null.
350-
351-
## Asynchronous Process Creation
352-
353-
These methods follow the common async programming patterns (accepting a
354-
callback or returning an EventEmitter).
355-
356-
### child_process.exec(command[, options], callback)
111+
### child_process.exec(command[, options][, callback])
357112

358113
* `command` {String} The command to run, with space-separated arguments
359114
* `options` {Object}
@@ -376,7 +131,8 @@ callback or returning an EventEmitter).
376131
* `stderr` {Buffer}
377132
* Return: ChildProcess object
378133

379-
Runs a command in a shell and buffers the output.
134+
Spawns a shell then executes the `command` within that shell, buffering any
135+
generated output.
380136

381137
const exec = require('child_process').exec;
382138
const child = exec('cat *.js bad_file | wc -l',
@@ -388,29 +144,35 @@ Runs a command in a shell and buffers the output.
388144
}
389145
});
390146

391-
The callback gets the arguments `(error, stdout, stderr)`. On success, `error`
392-
will be `null`. On error, `error` will be an instance of [`Error`][] and `error.code`
393-
will be the exit code of the child process, and `error.signal` will be set to the
394-
signal that terminated the process.
147+
If a `callback` function is provided, it is called with the arguments
148+
`(error, stdout, stderr)`. On success, `error` will be `null`. On error,
149+
`error` will be an instance of [`Error`][]. The `error.code` property will be
150+
the exit code of the child process while `error.signal` will be set to the
151+
signal that terminated the process. Any exit code other than `0` is considered
152+
to be an error.
395153

396-
There is a second optional argument to specify several options. The
397-
default options are
154+
The `options` argument may be passed as the second argument to customize how
155+
the process is spawned. The default options are:
398156

399-
{ encoding: 'utf8',
157+
{
158+
encoding: 'utf8',
400159
timeout: 0,
401160
maxBuffer: 200*1024,
402161
killSignal: 'SIGTERM',
403162
cwd: null,
404-
env: null }
163+
env: null
164+
}
405165

406-
If `timeout` is greater than 0, then it will kill the child process
407-
if it runs longer than `timeout` milliseconds. The child process is killed with
408-
`killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest
409-
amount of data (in bytes) allowed on stdout or stderr - if this value is
410-
exceeded then the child process is killed.
166+
If `timeout` is greater than `0`, the parent will send the the signal
167+
identified by the `killSignal` property (the default is `'SIGTERM'`) if the
168+
child runs longer than `timeout` milliseconds.
411169

412-
*Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not replace
413-
the existing process and uses a shell to execute the command.*
170+
The `maxBuffer` option specifies the largest amount of data (in bytes) allowed
171+
on stdout or stderr - if this value is exceeded then the child process is
172+
terminated.
173+
174+
*Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not
175+
replace the existing process and uses a shell to execute the command.*
414176

415177
### child_process.execFile(file[, args][, options][, callback])
416178

@@ -432,10 +194,21 @@ the existing process and uses a shell to execute the command.*
432194
* `stderr` {Buffer}
433195
* Return: ChildProcess object
434196

435-
This is similar to [`child_process.exec()`][] except it does not execute a
436-
subshell but rather the specified file directly. This makes it slightly
437-
leaner than [`child_process.exec()`][]. It has the same options.
197+
The `child_process.execFile()` method is similar to [`child_process.exec()`][]
198+
except that it does not first spawn a shell. Rather, the specified `command` is
199+
spawned directly as a new process making it slightly more efficient than
200+
[`child_process.exec()`][]. The same options are support by both
201+
`child_process.exec()` and `child_process.execFile()`.
438202

203+
const exec = require('child_process').execFile;
204+
const child = execFile('cat *.js bad_file | wc -l',
205+
(error, stdout, stderr) => {
206+
console.log(`stdout: ${stdout}`);
207+
console.log(`stderr: ${stderr}`);
208+
if (error !== null) {
209+
console.log(`exec error: ${error}`);
210+
}
211+
});
439212

440213
### child_process.fork(modulePath[, args][, options])
441214

@@ -455,23 +228,31 @@ leaner than [`child_process.exec()`][]. It has the same options.
455228
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
456229
* Return: ChildProcess object
457230

458-
This is a special case of the [`child_process.spawn()`][] functionality for
459-
spawning Node.js processes. In addition to having all the methods in a normal
460-
ChildProcess instance, the returned object has a communication channel built-in.
461-
See [`ChildProcess#send()`][] for details.
462-
463-
These child Node.js processes are still whole new instances of V8. Assume at
464-
least 30ms startup and 10mb memory for each new Node.js. That is, you cannot
465-
create many thousands of them.
466-
467-
The `execPath` property in the `options` object allows for a process to be
468-
created for the child rather than the current `node` executable. This should be
469-
done with care and by default will talk over the fd represented an
470-
environmental variable `NODE_CHANNEL_FD` on the child process. The input and
231+
The `child_process.fork()` method is a special case of
232+
[`child_process.spawn()`][] used specifically to spawn new Node.js processes.
233+
Like `child_process.spawn()`, a `ChildProcess` object is returned. The returned
234+
`ChildProcess` will have an additional communication channel built-in that
235+
allows messages to be passed back and forth between the parent and child. See
236+
[`ChildProcess#send()`][] for details.
237+
238+
It is important to keep in mind that spawned Node.js child processes are
239+
independent of the parent with exception of the IPC communication channel
240+
that is established between the two. Each process has it's own memory, with
241+
their own V8 instances. Because of the additional resource allocations
242+
required, spawning a large number of child Node.js processes is not
243+
recommended.
244+
245+
By default, `child_process.fork()` will spawn new Node.js instances using the
246+
`process.execPath` of the parent process. The `execPath` property in the
247+
`options` object allows for an alternative execution path to be used.
248+
249+
Node.js processes launched with a custom `execPath` will communicate with the
250+
parent process using the file descriptor (fd) identified using the
251+
environment variable `NODE_CHANNEL_FD` on the child process. The input and
471252
output on this fd is expected to be line delimited JSON objects.
472253

473-
*Note: Unlike the `fork()` POSIX system call, [`child_process.fork()`][] does not clone the
474-
current process.*
254+
*Note: Unlike the `fork()` POSIX system call, [`child_process.fork()`][] does
255+
not clone the current process.*
475256

476257
### child_process.spawn(command[, args][, options])
477258

@@ -489,12 +270,14 @@ current process.*
489270
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
490271
* return: {ChildProcess object}
491272

492-
Launches a new process with the given `command`, with command line arguments in
493-
`args`. If omitted, `args` defaults to an empty Array.
273+
The `child_process.spawn()` method spawns a new process using the given
274+
`command`, with command line arguments in `args`. If omitted, `args` defaults
275+
to an empty array.
494276

495-
The third argument is used to specify additional options, with these defaults:
277+
A third argument may be used to specify additional options, with these defaults:
496278

497-
{ cwd: undefined,
279+
{
280+
cwd: undefined,
498281
env: process.env
499282
}
500283

@@ -504,7 +287,8 @@ If not given, the default is to inherit the current working directory.
504287
Use `env` to specify environment variables that will be visible to the new
505288
process, the default is `process.env`.
506289

507-
Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code:
290+
Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
291+
exit code:
508292

509293
const spawn = require('child_process').spawn;
510294
const ls = spawn('ls', ['-lh', '/usr']);
@@ -569,18 +353,21 @@ Example of checking for failed exec:
569353

570354
#### options.detached
571355

572-
On Windows, this makes it possible for the child to continue running after the
573-
parent exits. The child will have a new console window (this cannot be
574-
disabled).
356+
On Windows, setting `options.detached` to `true` makes it possible for the
357+
child process to continue running after the parent exits. The child will have
358+
its own console window. *Once enabled for a child process, it cannot be
359+
disabled*.
575360

576-
On non-Windows, if the `detached` option is set, the child process will be made
577-
the leader of a new process group and session. Note that child processes may
578-
continue running after the parent exits whether they are detached or not. See
579-
`setsid(2)` for more information.
361+
On non-Windows platforms, if `options.detached` is set to `true`, the child
362+
process will be made the leader of a new process group and session. Note that
363+
child processes may continue running after the parent exits regardless of
364+
whether they are detached or not. See `setsid(2)` for more information.
580365

581-
By default, the parent will wait for the detached child to exit. To prevent
582-
the parent from waiting for a given `child`, use the `child.unref()` method,
583-
and the parent's event loop will not include the child in its reference count.
366+
By default, the parent will wait for the detached child to exit. To prevent
367+
the parent from waiting for a given `child`, use the `child.unref()` method.
368+
Doing so will cause the parent's event loop to not include the child in its
369+
reference count, allowing the parent to exit independently of the child, unless
370+
there is an established IPC channel between the child and parent.
584371

585372
Example of detaching a long-running process and redirecting its output to a
586373
file:
@@ -605,14 +392,23 @@ controlling terminal.
605392

606393
#### options.stdio
607394

608-
As a shorthand, the `stdio` argument may be one of the following strings:
395+
The `options.stdio` option is used to configure the pipes that are established
396+
between the parent and child process. By default, the child's stdin, stdout,
397+
and stderr are redirected to corresponding `child.stdin`, `child.stdout`, and
398+
`child.stderr` streams on the `ChildProcess` object. This is equivalent to
399+
setting the `options.stdio` equal to `['pipe', 'pipe', 'pipe']`.
400+
401+
For convenience, `options.stdio` may be one of the following strings:
609402

610-
* `'pipe'` - `['pipe', 'pipe', 'pipe']`, this is the default value
611-
* `'ignore'` - `['ignore', 'ignore', 'ignore']`
612-
* `'inherit'` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]`
403+
* `'pipe'` - equivalent to `['pipe', 'pipe', 'pipe']` (the default)
404+
* `'ignore'` - equivalent to `['ignore', 'ignore', 'ignore']`
405+
* `'inherit'` - equivalent to `[process.stdin, process.stdout, process.stderr]`
406+
or `[0,1,2]`
613407

614-
Otherwise, the `'stdio'` option to [`child_process.spawn()`][] is an array where each
615-
index corresponds to a fd in the child. The value is one of the following:
408+
Otherwise, the value of `option.stdio` is an array where each index corresponds
409+
to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
410+
and stderr, respectively. Additional fds can be specified to create additional
411+
pipes between the parent and child. The value is one of the following:
616412

617413
1. `'pipe'` - Create a pipe between the child process and the parent process.
618414
The parent end of the pipe is exposed to the parent as a property on the
@@ -622,13 +418,15 @@ index corresponds to a fd in the child. The value is one of the following:
622418
2. `'ipc'` - Create an IPC channel for passing messages/file descriptors
623419
between parent and child. A ChildProcess may have at most *one* IPC stdio
624420
file descriptor. Setting this option enables the ChildProcess.send() method.
625-
If the child writes JSON messages to this file descriptor, then this will
626-
trigger ChildProcess.on('message'). If the child is an Node.js program, then
627-
the presence of an IPC channel will enable process.send() and
628-
process.on('message').
629-
3. `'ignore'` - Do not set this file descriptor in the child. Note that Node.js
630-
will always open fd 0 - 2 for the processes it spawns. When any of these is
631-
ignored Node.js will open `/dev/null` and attach it to the child's fd.
421+
If the child writes JSON messages to this file descriptor, the
422+
`ChildProcess.on('message')` event handler will be triggered in the parent.
423+
If the child is a Node.js process, the presence of an IPC channel will enable
424+
`process.send()`, `process.disconnect()`, `process.on('disconnect')`, and
425+
`process.on('message')` within the child.
426+
3. `'ignore'` - Instructs Node.js to ignore the fd in the child. While Node.js
427+
will always open fds 0 - 2 for the processes it spawns, setting the fd to
428+
`'ignore'` will cause Node.js to open `/dev/null` and attach it to the
429+
child's fd.
632430
4. `Stream` object - Share a readable or writable stream that refers to a tty,
633431
file, socket, or a pipe with the child process. The stream's underlying
634432
file descriptor is duplicated in the child process to the fd that
@@ -652,16 +450,25 @@ Example:
652450
// Spawn child sharing only stderr
653451
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
654452

655-
// Open an extra fd=4, to interact with programs present a
453+
// Open an extra fd=4, to interact with programs presenting a
656454
// startd-style interface.
657455
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
658456

457+
*It is worth noting that when an IPC channel is established between the
458+
parent and child processes, and the child is a Node.js process, the child
459+
is launched with the IPC channel unreferenced (using `unref()`) until the
460+
child registers an event handler for the `process.on('disconnected')` event.
461+
This allows the child to exit normally without the process being held open
462+
by the open IPC channel.*
463+
659464
See also: [`child_process.exec()`][] and [`child_process.fork()`][]
660465

661466
## Synchronous Process Creation
662467

663-
These methods are **synchronous**, meaning they **WILL** block the event loop,
664-
pausing execution of your code until the spawned process exits.
468+
The `child_process.spawnSync()`, `child_process.execSync()`, and
469+
`child_process.execFileSync()` methods are **synchronous** and **WILL** block
470+
the Node.js event loop, pausing execution of any additional code until the
471+
spawned process exits.
665472

666473
Blocking calls like these are mostly useful for simplifying general purpose
667474
scripting tasks and for simplifying the loading/processing of application
@@ -688,11 +495,13 @@ configuration at startup.
688495
* `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
689496
* return: {Buffer|String} The stdout from the command
690497

691-
`execFileSync` will not return until the child process has fully closed. When a
692-
timeout has been encountered and `killSignal` is sent, the method won't return
693-
until the process has completely exited. That is to say, if the process handles
694-
the `SIGTERM` signal and doesn't exit, your process will wait until the child
695-
process has exited.
498+
The `child_process.execFileSync()` method is generally identical to
499+
`child_process.execFile()` with the exception that the method will not return
500+
until the child process has fully closed. When a timeout has been encountered
501+
and `killSignal` is sent, the method won't return until the process has
502+
completely exited. *Note that if the child process intercepts and handles
503+
the `SIGTERM` signal and does not exit, the parent process will still wait
504+
until the child process has exited.*
696505

697506
If the process times out, or has a non-zero exit code, this method ***will***
698507
throw. The [`Error`][] object will contain the entire result from
@@ -722,11 +531,13 @@ throw. The [`Error`][] object will contain the entire result from
722531
* `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
723532
* return: {Buffer|String} The stdout from the command
724533

725-
`execSync` will not return until the child process has fully closed. When a
726-
timeout has been encountered and `killSignal` is sent, the method won't return
727-
until the process has completely exited. That is to say, if the process handles
728-
the `SIGTERM` signal and doesn't exit, your process will wait until the child
729-
process has exited.
534+
The `child_process.execSync()` method is generally identical to
535+
`child_process.exec()` with the exception that the method will not return until
536+
the child process has fully closed. When a timeout has been encountered and
537+
`killSignal` is sent, the method won't return until the process has completely
538+
exited. *Note that if the child process intercepts and handles the `SIGTERM`
539+
signal and doesn't exit, the parent process will wait until the child
540+
process has exited.*
730541

731542
If the process times out, or has a non-zero exit code, this method ***will***
732543
throw. The [`Error`][] object will contain the entire result from
@@ -758,26 +569,370 @@ throw. The [`Error`][] object will contain the entire result from
758569
* `signal` {String} The signal used to kill the child process
759570
* `error` {Error} The error object if the child process failed or timed out
760571

761-
`spawnSync` will not return until the child process has fully closed. When a
762-
timeout has been encountered and `killSignal` is sent, the method won't return
763-
until the process has completely exited. That is to say, if the process handles
764-
the `SIGTERM` signal and doesn't exit, your process will wait until the child
572+
The `child_process.spawnSync()` method is generally identical to
573+
`child_process.spawn()` with the exception that the function will not return
574+
until the child process has fully closed. When a timeout has been encountered
575+
and `killSignal` is sent, the method won't return until the process has
576+
completely exited. Note that if the process intercepts and handles the
577+
`SIGTERM` signal and doesn't exit, the parent process will wait until the child
765578
process has exited.
766579

580+
## Class: ChildProcess
581+
582+
Instances of the `ChildProcess` class are [`EventEmitters`][] that represent
583+
spawned child processes.
584+
585+
Instances of `ChildProcess` are not intended to be created directly. Rather,
586+
use the [`child_process.spawn()`][], [`child_process.exec()`][],
587+
[`child_process.execFile()`][], or [`child_process.fork()`][] methods to create
588+
instances of `ChildProcess`.
589+
590+
### Event: 'close'
591+
592+
* `code` {Number} the exit code if the child exited on its own.
593+
* `signal` {String} the signal by which the child process was terminated.
594+
595+
The `'close'` event is emitted when the stdio streams of a child process have
596+
been closed. This is distinct from the `'exit'` event, since multiple
597+
processes might share the same stdio streams.
598+
599+
### Event: 'disconnect'
600+
601+
The `'disconnect'` event is emitted after calling the
602+
`ChildProcess.disconnect()` method in the parent or child process. After
603+
disconnecting it is no longer possible to send or receive messages, and the
604+
`ChildProcess.connected` property is false.
605+
606+
### Event: 'error'
607+
608+
* `err` {Error Object} the error.
609+
610+
The `'error'` event is emitted whenever:
611+
612+
1. The process could not be spawned, or
613+
2. The process could not be killed, or
614+
3. Sending a message to the child process failed.
615+
616+
Note that the `'exit'` event may or may not fire after an error has occurred.
617+
If you are listening to both the `'exit'` and `'error'` events, it is important
618+
to guard against accidentally invoking handler functions multiple times.
619+
620+
See also [`ChildProcess#kill()`][] and [`ChildProcess#send()`][].
621+
622+
### Event: 'exit'
623+
624+
* `code` {Number} the exit code if the child exited on its own.
625+
* `signal` {String} the signal by which the child process was terminated.
626+
627+
The `'exit'` event is emitted after the child process ends. If the process
628+
exited, `code` is the final exit code of the process, otherwise `null`. If the
629+
process terminated due to receipt of a signal, `signal` is the string name of
630+
the signal, otherwise `null`. One of the two will always be non-null.
631+
632+
Note that when the `'exit'` event is triggered, child process stdio streams
633+
might still be open.
634+
635+
Also, note that Node.js establishes signal handlers for `SIGINT` and
636+
`SIGTERM` and Node.js processes will not terminate immediately due to receipt
637+
of those signals. Rather, Node.js will perform a sequence of cleanup actions
638+
and then will re-raise the handled signal.
639+
640+
See `waitpid(2)`.
641+
642+
### Event: 'message'
643+
644+
* `message` {Object} a parsed JSON object or primitive value.
645+
* `sendHandle` {Handle object} a [`net.Socket`][] or [`net.Server`][] object, or
646+
undefined.
647+
648+
The `'message'` event is triggered when a child process uses `process.send()`
649+
to send messages.
650+
651+
### child.connected
652+
653+
* {Boolean} Set to false after `.disconnect` is called
654+
655+
The `child.connected` property indicates whether it is still possible to send
656+
and receive messages from a child process. When `child.connected` is false, it
657+
is no longer possible to send or receive messages.
658+
659+
### child.disconnect()
660+
661+
Closes the IPC channel between parent and child, allowing the child to exit
662+
gracefully once there are no other connections keeping it alive. After calling
663+
this method the `child.connected` and `process.connected` properties in both
664+
the parent and child (respectively) will be set to `false`, and it will be no
665+
longer possible to pass messages between the processes.
666+
667+
The `'disconnect'` event will be emitted when there are no messages in the
668+
process of being received. This will most often be triggered immediately after
669+
calling `child.disconnect()`.
670+
671+
Note that when the child process is a Node.js instance (e.g. spawned using
672+
[`child_process.fork()`]), the `process.disconnect()` method can be invoked
673+
within the child process to close the IPC channel as well.
674+
675+
### child.kill([signal])
676+
677+
* `signal` {String}
678+
679+
The `child.kill()` methods sends a signal to the child process. If no argument
680+
is given, the process will be sent the `'SIGTERM'` signal. See `signal(7)` for
681+
a list of available signals.
682+
683+
const spawn = require('child_process').spawn;
684+
const grep = spawn('grep', ['ssh']);
685+
686+
grep.on('close', (code, signal) => {
687+
console.log(
688+
`child process terminated due to receipt of signal ${signal}`);
689+
});
690+
691+
// Send SIGHUP to process
692+
grep.kill('SIGHUP');
693+
694+
The `ChildProcess` object may emit an `'error'` event if the signal cannot be
695+
delivered. Sending a signal to a child process that has already exited is not
696+
an error but may have unforeseen consequences. Specifically, if the process
697+
identifier (PID) has been reassigned to another process, the signal will be
698+
delivered to that process instead which can have unexpected results.
699+
700+
Note that while the function is called `kill`, the signal delivered to the
701+
child process may not actually terminate the process.
702+
703+
See `kill(2)`
704+
705+
### child.pid
706+
707+
* {Integer}
708+
709+
Returns the process identifier (PID) of the child process.
710+
711+
Example:
712+
713+
const spawn = require('child_process').spawn;
714+
const grep = spawn('grep', ['ssh']);
715+
716+
console.log(`Spawned child pid: ${grep.pid}`);
717+
grep.stdin.end();
718+
719+
### child.send(message[, sendHandle][, callback])
720+
721+
* `message` {Object}
722+
* `sendHandle` {Handle object}
723+
* `callback` {Function}
724+
* Return: Boolean
725+
726+
When an IPC channel has been established between the parent and child (
727+
i.e. when using [`child_process.fork()`][]), the `child.send()` method can be
728+
used to send messages to the child process. When the child process is a Node.js
729+
instance, these messages can be received via the `process.on('message')` event.
730+
731+
For example, in the parent script:
732+
733+
const cp = require('child_process');
734+
const n = cp.fork(`${__dirname}/sub.js`);
735+
736+
n.on('message', (m) => {
737+
console.log('PARENT got message:', m);
738+
});
739+
740+
n.send({ hello: 'world' });
741+
742+
And then the child script, `'sub.js'` might look like this:
743+
744+
process.on('message', (m) => {
745+
console.log('CHILD got message:', m);
746+
});
747+
748+
process.send({ foo: 'bar' });
749+
750+
Child Node.js processes will have a `process.send()` method of their own that
751+
allows the child to send messages back to the parent.
752+
753+
There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
754+
containing a `NODE_` prefix in its `cmd` property are considered to be reserved
755+
for use within Node.js core and will not be emitted in the child's
756+
`process.on('message')` event. Rather, such messages are emitted using the
757+
`process.on('internalMessage')` event and are consumed internally by Node.js.
758+
Applications should avoid using such messages or listening for
759+
`'internalMessage'` events as it is subject to change without notice.
760+
761+
The optional `sendHandle` argument that may be passed to `child.send()` is for
762+
passing a TCP server or socket object to the child process. The child will
763+
receive the object as the second argument passed to the callback function
764+
registered on the `process.on('message')` event.
765+
766+
The optional `callback` is a function that is invoked after the message is
767+
sent but before the child may have received it. The function is called with a
768+
single argument: `null` on success, or an [`Error`][] object on failure.
769+
770+
If no `callback` function is provided and the message cannot be sent, an
771+
`'error'` event will be emitted by the `ChildProcess` object. This can happen,
772+
for instance, when the child process has already exited.
773+
774+
`child.send()` will return `false` if the channel has closed or when the
775+
backlog of unsent messages exceeds a threshold that makes it unwise to send
776+
more. Otherwise, the method returns `true`. The `callback` function can be
777+
used to implement flow control.
778+
779+
#### Example: sending a server object
780+
781+
The `sendHandle` argument can be used, for instance, to pass the handle of
782+
a TSCP server object to the child process as illustrated in the example below:
783+
784+
const child = require('child_process').fork('child.js');
785+
786+
// Open up the server object and send the handle.
787+
const server = require('net').createServer();
788+
server.on('connection', (socket) => {
789+
socket.end('handled by parent');
790+
});
791+
server.listen(1337, () => {
792+
child.send('server', server);
793+
});
794+
795+
The child would then receive the server object as:
796+
797+
process.on('message', (m, server) => {
798+
if (m === 'server') {
799+
server.on('connection', (socket) => {
800+
socket.end('handled by child');
801+
});
802+
}
803+
});
804+
805+
Once the server is now shared between the parent and child, some connections
806+
can be handled by the parent and some by the child.
807+
808+
While the example above uses a server created using the `net` module, `dgram`
809+
module servers use exactly the same workflow with the exceptions of listening on
810+
a `'message'` event instead of `'connection'` and using `server.bind` instead of
811+
`server.listen`. This is, however, currently only supported on UNIX platforms.
812+
813+
#### Example: sending a socket object
814+
815+
Similarly, the `sendHandler` argument can be used to pass the handle of a
816+
socket to the child process. The example below spawns two children that each
817+
handle connections with "normal" or "special" priority:
818+
819+
const normal = require('child_process').fork('child.js', ['normal']);
820+
const special = require('child_process').fork('child.js', ['special']);
821+
822+
// Open up the server and send sockets to child
823+
const server = require('net').createServer();
824+
server.on('connection', (socket) => {
825+
826+
// If this is special priority
827+
if (socket.remoteAddress === '74.125.127.100') {
828+
special.send('socket', socket);
829+
return;
830+
}
831+
// This is normal priority
832+
normal.send('socket', socket);
833+
});
834+
server.listen(1337);
835+
836+
The `child.js` would receive the socket handle as the second argument passed
837+
to the event callback function:
838+
839+
process.on('message', (m, socket) => {
840+
if (m === 'socket') {
841+
socket.end(`Request handled with ${process.argv[2]} priority`);
842+
}
843+
});
844+
845+
Once a socket has been passed to a child, the parent is no longer capable of
846+
tracking when the socket is destroyed. To indicate this, the `.connections`
847+
property becomes `null`. It is recommended not to use `.maxConnections` when
848+
this occurs.
849+
850+
### child.stderr
851+
852+
* {Stream object}
853+
854+
A `Readable Stream` that represents the child process's `stderr`.
855+
856+
If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
857+
then this will be `undefined`.
858+
859+
`child.stderr` is an alias for `child.stdio[2]`. Both properties will refer to
860+
the same value.
861+
862+
### child.stdin
863+
864+
* {Stream object}
865+
866+
A `Writable Stream` that represents the child process's `stdin`.
867+
868+
*Note that if a child process waits to read all of its input, the child will not
869+
continue until this stream has been closed via `end()`.*
870+
871+
If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
872+
then this will be `undefined`.
873+
874+
`child.stdin` is an alias for `child.stdio[0]`. Both properties will refer to
875+
the same value.
876+
877+
### child.stdio
878+
879+
* {Array}
880+
881+
A sparse array of pipes to the child process, corresponding with positions in
882+
the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
883+
to the value `'pipe'`. Note that `child.stdio[0]`, `child.stdio[1]`, and
884+
`child.stdio[2]` are also available as `child.stdin`, `child.stdout`, and
885+
`child.stderr`, respectively.
886+
887+
In the following example, only the child's fd `1` (stdout) is configured as a
888+
pipe, so only the parent's `child.stdio[1]` is a stream, all other values in
889+
the array are `null`.
890+
891+
const assert = require('assert');
892+
const fs = require('fs');
893+
const child_process = require('child_process');
894+
895+
const child = child_process.spawn('ls', {
896+
stdio: [
897+
0, // Use parents stdin for child
898+
'pipe', // Pipe child's stdout to parent
899+
fs.openSync('err.out', 'w') // Direct child's stderr to a file
900+
]
901+
});
902+
903+
assert.equal(child.stdio[0], null);
904+
assert.equal(child.stdio[0], child.stdin);
905+
906+
assert(child.stdout);
907+
assert.equal(child.stdio[1], child.stdout);
908+
909+
assert.equal(child.stdio[2], null);
910+
assert.equal(child.stdio[2], child.stderr);
911+
912+
### child.stdout
913+
914+
* {Stream object}
915+
916+
A `Readable Stream` that represents the child process's `stdout`.
917+
918+
If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
919+
then this will be `undefined`.
920+
921+
`child.stdout` is an alias for `child.stdio[1]`. Both properties will refer
922+
to the same value.
923+
924+
[`popen(3)`]: http://linux.die.net/man/3/popen
767925
[`child_process.exec()`]: #child_process_child_process_exec_command_options_callback
926+
[`child_process.execFile()`]: #child_process_child_process_execfile_file_args_options_callback
768927
[`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
769928
[`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options
770929
[`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options
771930
[`ChildProcess#kill()`]: #child_process_child_kill_signal
772931
[`ChildProcess#send()`]: #child_process_child_send_message_sendhandle_callback
773932
[`Error`]: errors.html#errors_class_error
774-
[`EventEmitter`]: events.html#events_class_events_eventemitter
775-
[`exec()`]: #child_process_child_process_exec_command_options_callback
776-
[`execFile()`]: #child_process_child_process_execfile_file_args_options_callback
777-
[`fork()`]: #child_process_child_process_fork_modulepath_args_options
933+
[`EventEmitters`]: events.html#events_class_events_eventemitter
778934
[`net.Server`]: net.html#net_class_net_server
779935
[`net.Socket`]: net.html#net_class_net_socket
780-
[`spawn()`]: #child_process_child_process_spawn_command_args_options
781936
[`stdio`]: #child_process_options_stdio
782937
[below]: #child_process_asynchronous_process_creation
783938
[synchronous counterparts]: #child_process_synchronous_process_creation

0 commit comments

Comments
 (0)
Please sign in to comment.