Browse Source

doc: improvements to child_process, process docs

Sort links in lexical order. Add missing links.
Add `disconnect` event description in Process doc.
Fix typos.

R-URL: https://github.com/nodejs/node/pull/5075
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Robert Jefe Lindstädt <robert.lindstaedt@gmail.com>
Reviewed-By: Roman Reiss <me@silverwind.io>
process-exit-stdio-flushing
Alexander Makarenko 9 years ago
committed by James M Snell
parent
commit
f85412d49b
  1. 221
      doc/api/child_process.md
  2. 60
      doc/api/process.md

221
doc/api/child_process.md

@ -3,8 +3,8 @@
Stability: 2 - Stable
The `child_process` module provides the ability to spawn child processes in
a manner that is similar, but not identical, to [`popen(3)`][]. This capability
is primarily provided by the `child_process.spawn()` function:
a manner that is similar, but not identical, to popen(3). This capability
is primarily provided by the [`child_process.spawn()`][] function:
```js
const spawn = require('child_process').spawn;
@ -29,27 +29,27 @@ through these pipes in a non-blocking way. *Note, however, that some programs
use line-buffered I/O internally. While that does not affect Node.js, it can
mean that data sent to the child process may not be immediately consumed.*
The `child_process.spawn()` method spawns the child process asynchronously,
without blocking the Node.js event loop. The `child_process.spawnSync()`
The [`child_process.spawn()`][] method spawns the child process asynchronously,
without blocking the Node.js event loop. The [`child_process.spawnSync()`][]
function provides equivalent functionality in a synchronous manner that blocks
the event loop until the spawned process either exits or is terminated.
For convenience, the `child_process` module provides a handful of synchronous
and asynchronous alternatives to [`child_process.spawn()`][] and
[`child_process.spawnSync()`][]. *Note that each of these alternatives are
implemented on top of `child_process.spawn()` or `child_process.spawnSync()`.*
implemented on top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].*
* `child_process.exec()`: spawns a shell and runs a command within that shell,
* [`child_process.exec()`][]: spawns a shell and runs a command within that shell,
passing the `stdout` and `stderr` to a callback function when complete.
* `child_process.execFile()`: similar to `child_process.exec()` except that
* [`child_process.execFile()`][]: similar to [`child_process.exec()`][] except that
it spawns the command directly without first spawning a shell.
* `child_process.fork()`: spawns a new Node.js process and invokes a
* [`child_process.fork()`][]: spawns a new Node.js process and invokes a
specified module with an IPC communication channel established that allows
sending messages between parent and child.
* `child_process.execSync()`: a synchronous version of
`child_process.exec()` that *will* block the Node.js event loop.
* `child_process.execFileSync()`: a synchronous version of
`child_process.execFile()` that *will* block the Node.js event loop.
* [`child_process.execSync()`][]: a synchronous version of
[`child_process.exec()`][] that *will* block the Node.js event loop.
* [`child_process.execFileSync()`][]: a synchronous version of
[`child_process.execFile()`][] that *will* block the Node.js event loop.
For certain use cases, such as automating shell scripts, the
[synchronous counterparts][] may be more convenient. In many cases, however,
@ -58,8 +58,8 @@ stalling the event loop while spawned processes complete.
## Asynchronous Process Creation
The `child_process.spawn()`, `child_process.fork()`, `child_process.exec()`,
and `child_process.execFile()` methods all follow the idiomatic asynchronous
The [`child_process.spawn()`][], [`child_process.fork()`][], [`child_process.exec()`][],
and [`child_process.execFile()`][] methods all follow the idiomatic asynchronous
programming pattern typical of other Node.js APIs.
Each of the methods returns a [`ChildProcess`][] instance. These objects
@ -67,22 +67,22 @@ implement the Node.js [`EventEmitter`][] API, allowing the parent process to
register listener functions that are called when certain events occur during
the life cycle of the child process.
The `child_process.exec()` and `child_process.execFile()` methods additionally
The [`child_process.exec()`][] and [`child_process.execFile()`][] methods additionally
allow for an optional `callback` function to be specified that is invoked
when the child process terminates.
### Spawning `.bat` and `.cmd` files on Windows
The importance of the distinction between `child_process.exec()` and
`child_process.execFile()` can vary based on platform. On Unix-type operating
systems (Unix, Linux, OSX) `child_process.execFile()` can be more efficient
The importance of the distinction between [`child_process.exec()`][] and
[`child_process.execFile()`][] can vary based on platform. On Unix-type operating
systems (Unix, Linux, OSX) [`child_process.execFile()`][] can be more efficient
because it does not spawn a shell. On Windows, however, `.bat` and `.cmd`
files are not executable on their own without a terminal, and therefore cannot
be launched using `child_process.execFile()`. When running on Windows, `.bat`
and `.cmd` files can be invoked using `child_process.spawn()` with the `shell`
option set, with `child_process.exec()`, or by spawning `cmd.exe` and passing
be launched using [`child_process.execFile()`][]. When running on Windows, `.bat`
and `.cmd` files can be invoked using [`child_process.spawn()`][] with the `shell`
option set, with [`child_process.exec()`][], or by spawning `cmd.exe` and passing
the `.bat` or `.cmd` file as an argument (which is what the `shell` option and
`child_process.exec()` do).
[`child_process.exec()`][] do).
```js
// On Windows Only ...
@ -118,15 +118,15 @@ exec('my.bat', (err, stdout, stderr) => {
* `options` {Object}
* `cwd` {String} Current working directory of the child process
* `env` {Object} Environment key-value pairs
* `encoding` {String} (Default: 'utf8')
* `encoding` {String} (Default: `'utf8'`)
* `shell` {String} Shell to execute the command with
(Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should
(Default: `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows, The shell should
understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows,
command line parsing should be compatible with `cmd.exe`.)
* `timeout` {Number} (Default: 0)
* `timeout` {Number} (Default: `0`)
* [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on
stdout or stderr - if exceeded child process is killed (Default: `200*1024`)
* `killSignal` {String} (Default: 'SIGTERM')
stdout or stderr - if exceeded child process is killed (Default: `200\*1024`)
* `killSignal` {String} (Default: `'SIGTERM'`)
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* `callback` {Function} called with the output when process terminates
@ -182,7 +182,7 @@ If `timeout` is greater than `0`, the parent will send the the signal
identified by the `killSignal` property (the default is `'SIGTERM'`) if the
child runs longer than `timeout` milliseconds.
*Note: Unlike the `exec()` POSIX system call, `child_process.exec()` does not
*Note: Unlike the exec(3) POSIX system call, `child_process.exec()` does not
replace the existing process and uses a shell to execute the command.*
### child_process.execFile(file[, args][, options][, callback])
@ -192,11 +192,11 @@ replace the existing process and uses a shell to execute the command.*
* `options` {Object}
* `cwd` {String} Current working directory of the child process
* `env` {Object} Environment key-value pairs
* `encoding` {String} (Default: 'utf8')
* `timeout` {Number} (Default: 0)
* `encoding` {String} (Default: `'utf8'`)
* `timeout` {Number} (Default: `0`)
* [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on
stdout or stderr - if exceeded child process is killed (Default: 200\*1024)
* `killSignal` {String} (Default: 'SIGTERM')
stdout or stderr - if exceeded child process is killed (Default: `200\*1024`)
* `killSignal` {String} (Default: `'SIGTERM'`)
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* `callback` {Function} called with the output when process terminates
@ -210,7 +210,7 @@ except that it does not spawn a shell. Rather, the specified executable `file`
is spawned directly as a new process making it slightly more efficient than
[`child_process.exec()`][].
The same options as `child_process.exec()` are supported. Since a shell is not
The same options as [`child_process.exec()`][] are supported. Since a shell is not
spawned, behaviors such as I/O redirection and file globbing are not supported.
```js
@ -240,20 +240,20 @@ the callback instead.
* `execPath` {String} Executable used to create the child process
* `execArgv` {Array} List of string arguments passed to the executable
(Default: `process.execArgv`)
* `silent` {Boolean} If true, stdin, stdout, and stderr of the child will be
* `silent` {Boolean} If `true`, stdin, stdout, and stderr of the child will be
piped to the parent, otherwise they will be inherited from the parent, see
the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s
[`stdio`][] for more details (default is false)
[`stdio`][] for more details (Default: `false`)
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* Return: {ChildProcess}
The `child_process.fork()` method is a special case of
[`child_process.spawn()`][] used specifically to spawn new Node.js processes.
Like `child_process.spawn()`, a `ChildProcess` object is returned. The returned
`ChildProcess` will have an additional communication channel built-in that
Like [`child_process.spawn()`][], a [`ChildProcess`][] object is returned. The returned
[`ChildProcess`][] will have an additional communication channel built-in that
allows messages to be passed back and forth between the parent and child. See
[`ChildProcess#send()`][] for details.
[`child.send()`][] for details.
It is important to keep in mind that spawned Node.js child processes are
independent of the parent with exception of the IPC communication channel
@ -263,7 +263,7 @@ required, spawning a large number of child Node.js processes is not
recommended.
By default, `child_process.fork()` will spawn new Node.js instances using the
`process.execPath` of the parent process. The `execPath` property in the
[`process.execPath`][] of the parent process. The `execPath` property in the
`options` object allows for an alternative execution path to be used.
Node.js processes launched with a custom `execPath` will communicate with the
@ -271,7 +271,7 @@ parent process using the file descriptor (fd) identified using the
environment variable `NODE_CHANNEL_FD` on the child process. The input and
output on this fd is expected to be line delimited JSON objects.
*Note: Unlike the `fork()` POSIX system call, [`child_process.fork()`][] does
*Note: Unlike the fork(2) POSIX system call, `child_process.fork()` does
not clone the current process.*
### child_process.spawn(command[, args][, options])
@ -282,14 +282,14 @@ not clone the current process.*
* `cwd` {String} Current working directory of the child process
* `env` {Object} Environment key-value pairs
* `stdio` {Array|String} Child's stdio configuration. (See
[`options.stdio`][])
[`options.stdio`][`stdio`])
* `detached` {Boolean} Prepare child to run independently of its parent
process. Specific behavior depends on the platform, see
[`options.detached`][])
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* `shell` {Boolean|String} If `true`, runs `command` inside of a shell. Uses
'/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be
`'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be
specified as a string. The shell should understand the `-c` switch on UNIX,
or `/s /c` on Windows. Defaults to `false` (no shell).
* return: {ChildProcess}
@ -311,7 +311,7 @@ Use `cwd` to specify the working directory from which the process is spawned.
If not given, the default is to inherit the current working directory.
Use `env` to specify environment variables that will be visible to the new
process, the default is `process.env`.
process, the default is [`process.env`][].
Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
exit code:
@ -334,7 +334,7 @@ ls.on('close', (code) => {
```
Example: A very elaborate way to run 'ps ax | grep ssh'
Example: A very elaborate way to run `ps ax | grep ssh`
```js
const spawn = require('child_process').spawn;
@ -393,7 +393,7 @@ disabled*.
On non-Windows platforms, if `options.detached` is set to `true`, the child
process will be made the leader of a new process group and session. Note that
child processes may continue running after the parent exits regardless of
whether they are detached or not. See `setsid(2)` for more information.
whether they are detached or not. See setsid(2) for more information.
By default, the parent will wait for the detached child to exit. To prevent
the parent from waiting for a given `child`, use the `child.unref()` method.
@ -441,8 +441,8 @@ child.unref();
The `options.stdio` option is used to configure the pipes that are established
between the parent and child process. By default, the child's stdin, stdout,
and stderr are redirected to corresponding `child.stdin`, `child.stdout`, and
`child.stderr` streams on the `ChildProcess` object. This is equivalent to
and stderr are redirected to corresponding [`child.stdin`][], [`child.stdout`][], and
[`child.stderr`][] streams on the [`ChildProcess`][] object. This is equivalent to
setting the `options.stdio` equal to `['pipe', 'pipe', 'pipe']`.
For convenience, `options.stdio` may be one of the following strings:
@ -452,29 +452,29 @@ For convenience, `options.stdio` may be one of the following strings:
* `'inherit'` - equivalent to `[process.stdin, process.stdout, process.stderr]`
or `[0,1,2]`
Otherwise, the value of `option.stdio` is an array where each index corresponds
Otherwise, the value of `options.stdio` is an array where each index corresponds
to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
and stderr, respectively. Additional fds can be specified to create additional
pipes between the parent and child. The value is one of the following:
1. `'pipe'` - Create a pipe between the child process and the parent process.
The parent end of the pipe is exposed to the parent as a property on the
`child_process` object as `ChildProcess.stdio[fd]`. Pipes created for
fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
and ChildProcess.stderr, respectively.
`child_process` object as [`child.stdio[fd]`][`stdio`]. Pipes created for
fds 0 - 2 are also available as [`child.stdin`][], [`child.stdout`][]
and [`child.stderr`][], respectively.
2. `'ipc'` - Create an IPC channel for passing messages/file descriptors
between parent and child. A ChildProcess may have at most *one* IPC stdio
file descriptor. Setting this option enables the ChildProcess.send() method.
between parent and child. A [`ChildProcess`][] may have at most *one* IPC stdio
file descriptor. Setting this option enables the [`child.send()`][] method.
If the child writes JSON messages to this file descriptor, the
`ChildProcess.on('message')` event handler will be triggered in the parent.
[`child.on('message')`][`'message'`] event handler will be triggered in the parent.
If the child is a Node.js process, the presence of an IPC channel will enable
`process.send()`, `process.disconnect()`, `process.on('disconnect')`, and
`process.on('message')` within the child.
[`process.send()`][], [`process.disconnect()`][], [`process.on('disconnect')`][], and
[`process.on('message')`] within the child.
3. `'ignore'` - Instructs Node.js to ignore the fd in the child. While Node.js
will always open fds 0 - 2 for the processes it spawns, setting the fd to
`'ignore'` will cause Node.js to open `/dev/null` and attach it to the
child's fd.
4. `Stream` object - Share a readable or writable stream that refers to a tty,
4. {Stream} object - Share a readable or writable stream that refers to a tty,
file, socket, or a pipe with the child process. The stream's underlying
file descriptor is duplicated in the child process to the fd that
corresponds to the index in the `stdio` array. Note that the stream must
@ -482,7 +482,7 @@ pipes between the parent and child. The value is one of the following:
event has occurred).
5. Positive integer - The integer value is interpreted as a file descriptor
that is is currently open in the parent process. It is shared with the child
process, similar to how `Stream` objects can be shared.
process, similar to how {Stream} objects can be shared.
6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other
words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
default is `'ignore'`.
@ -506,7 +506,7 @@ spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
*It is worth noting that when an IPC channel is established between the
parent and child processes, and the child is a Node.js process, the child
is launched with the IPC channel unreferenced (using `unref()`) until the
child registers an event handler for the `process.on('disconnected')` event.
child registers an event handler for the [`process.on('disconnect')`][] event.
This allows the child to exit normally without the process being held open
by the open IPC channel.*
@ -514,8 +514,8 @@ See also: [`child_process.exec()`][] and [`child_process.fork()`][]
## Synchronous Process Creation
The `child_process.spawnSync()`, `child_process.execSync()`, and
`child_process.execFileSync()` methods are **synchronous** and **WILL** block
The [`child_process.spawnSync()`][], [`child_process.execSync()`][], and
[`child_process.execFileSync()`][] methods are **synchronous** and **WILL** block
the Node.js event loop, pausing execution of any additional code until the
spawned process exits.
@ -532,23 +532,23 @@ configuration at startup.
* `input` {String|Buffer} The value which will be passed as stdin to the
spawned process
- supplying this value will override `stdio[0]`
* `stdio` {Array} Child's stdio configuration. (Default: 'pipe')
* `stdio` {Array} Child's stdio configuration. (Default: `'pipe'`)
- `stderr` by default will be output to the parent process' stderr unless
`stdio` is specified
* `env` {Object} Environment key-value pairs
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* `timeout` {Number} In milliseconds the maximum amount of time the process
is allowed to run. (Default: undefined)
is allowed to run. (Default: `undefined`)
* `killSignal` {String} The signal value to be used when the spawned process
will be killed. (Default: 'SIGTERM')
will be killed. (Default: `'SIGTERM'`)
* [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on
stdout or stderr - if exceeded child process is killed
* `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: 'buffer')
* `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: `'buffer'`)
* return: {Buffer|String} The stdout from the command
The `child_process.execFileSync()` method is generally identical to
`child_process.execFile()` with the exception that the method will not return
[`child_process.execFile()`][] with the exception that the method will not return
until the child process has fully closed. When a timeout has been encountered
and `killSignal` is sent, the method won't return until the process has
completely exited. *Note that if the child process intercepts and handles
@ -567,28 +567,28 @@ throw. The [`Error`][] object will contain the entire result from
* `input` {String|Buffer} The value which will be passed as stdin to the
spawned process
- supplying this value will override `stdio[0]`
* `stdio` {Array} Child's stdio configuration. (Default: 'pipe')
* `stdio` {Array} Child's stdio configuration. (Default: `'pipe'`)
- `stderr` by default will be output to the parent process' stderr unless
`stdio` is specified
* `env` {Object} Environment key-value pairs
* `shell` {String} Shell to execute the command with
(Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should
(Default: `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows, The shell should
understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows,
command line parsing should be compatible with `cmd.exe`.)
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* `timeout` {Number} In milliseconds the maximum amount of time the process
is allowed to run. (Default: undefined)
is allowed to run. (Default: `undefined`)
* `killSignal` {String} The signal value to be used when the spawned process
will be killed. (Default: 'SIGTERM')
will be killed. (Default: `'SIGTERM'`)
* [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on
stdout or stderr - if exceeded child process is killed
* `encoding` {String} The encoding used for all stdio inputs and outputs.
(Default: 'buffer')
(Default: `'buffer'`)
* return: {Buffer|String} The stdout from the command
The `child_process.execSync()` method is generally identical to
`child_process.exec()` with the exception that the method will not return until
[`child_process.exec()`][] with the exception that the method will not return until
the child process has fully closed. When a timeout has been encountered and
`killSignal` is sent, the method won't return until the process has completely
exited. *Note that if the child process intercepts and handles the `SIGTERM`
@ -613,15 +613,15 @@ throw. The [`Error`][] object will contain the entire result from
* `uid` {Number} Sets the user identity of the process. (See setuid(2).)
* `gid` {Number} Sets the group identity of the process. (See setgid(2).)
* `timeout` {Number} In milliseconds the maximum amount of time the process
is allowed to run. (Default: undefined)
is allowed to run. (Default: `undefined`)
* `killSignal` {String} The signal value to be used when the spawned process
will be killed. (Default: 'SIGTERM')
will be killed. (Default: `'SIGTERM'`)
* [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on
stdout or stderr - if exceeded child process is killed
* `encoding` {String} The encoding used for all stdio inputs and outputs.
(Default: 'buffer')
(Default: `'buffer'`)
* `shell` {Boolean|String} If `true`, runs `command` inside of a shell. Uses
'/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be
`'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be
specified as a string. The shell should understand the `-c` switch on UNIX,
or `/s /c` on Windows. Defaults to `false` (no shell).
* return: {Object}
@ -634,7 +634,7 @@ throw. The [`Error`][] object will contain the entire result from
* `error` {Error} The error object if the child process failed or timed out
The `child_process.spawnSync()` method is generally identical to
`child_process.spawn()` with the exception that the function will not return
[`child_process.spawn()`][] with the exception that the function will not return
until the child process has fully closed. When a timeout has been encountered
and `killSignal` is sent, the method won't return until the process has
completely exited. Note that if the process intercepts and handles the
@ -643,7 +643,7 @@ process has exited.
## Class: ChildProcess
Instances of the `ChildProcess` class are [`EventEmitters`][] that represent
Instances of the `ChildProcess` class are [`EventEmitters`][`EventEmitter`] that represent
spawned child processes.
Instances of `ChildProcess` are not intended to be created directly. Rather,
@ -657,15 +657,15 @@ instances of `ChildProcess`.
* `signal` {String} the signal by which the child process was terminated.
The `'close'` event is emitted when the stdio streams of a child process have
been closed. This is distinct from the `'exit'` event, since multiple
been closed. This is distinct from the [`'exit'`][] event, since multiple
processes might share the same stdio streams.
### Event: 'disconnect'
The `'disconnect'` event is emitted after calling the
`ChildProcess.disconnect()` method in the parent or child process. After
[`child.disconnect()`][] method in parent process or [`process.disconnect()`][] in child process. After
disconnecting it is no longer possible to send or receive messages, and the
`ChildProcess.connected` property is false.
[`child.connected`][] property is `false`.
### Event: 'error'
@ -681,7 +681,7 @@ Note that the `'exit'` event may or may not fire after an error has occurred.
If you are listening to both the `'exit'` and `'error'` events, it is important
to guard against accidentally invoking handler functions multiple times.
See also [`ChildProcess#kill()`][] and [`ChildProcess#send()`][].
See also [`child.kill()`][] and [`child.send()`][].
### Event: 'exit'
@ -701,7 +701,7 @@ Also, note that Node.js establishes signal handlers for `SIGINT` and
of those signals. Rather, Node.js will perform a sequence of cleanup actions
and then will re-raise the handled signal.
See `waitpid(2)`.
See waitpid(2).
### Event: 'message'
@ -709,15 +709,15 @@ See `waitpid(2)`.
* `sendHandle` {Handle} a [`net.Socket`][] or [`net.Server`][] object, or
undefined.
The `'message'` event is triggered when a child process uses `process.send()`
The `'message'` event is triggered when a child process uses [`process.send()`][]
to send messages.
### child.connected
* {Boolean} Set to false after `.disconnect` is called
* {Boolean} Set to `false` after `child.disconnect()` is called
The `child.connected` property indicates whether it is still possible to send
and receive messages from a child process. When `child.connected` is false, it
and receive messages from a child process. When `child.connected` is `false`, it
is no longer possible to send or receive messages.
### child.disconnect()
@ -757,7 +757,7 @@ grep.on('close', (code, signal) => {
grep.kill('SIGHUP');
```
The `ChildProcess` object may emit an `'error'` event if the signal cannot be
The [`ChildProcess`][] object may emit an [`'error'`][] event if the signal cannot be
delivered. Sending a signal to a child process that has already exited is not
an error but may have unforeseen consequences. Specifically, if the process
identifier (PID) has been reassigned to another process, the signal will be
@ -766,7 +766,7 @@ delivered to that process instead which can have unexpected results.
Note that while the function is called `kill`, the signal delivered to the
child process may not actually terminate the process.
See `kill(2)` for reference.
See kill(2) for reference.
Also note: on Linux, child processes of child processes will not be terminated
when attempting to kill their parent. This is likely to happen when running a
@ -817,7 +817,7 @@ grep.stdin.end();
When an IPC channel has been established between the parent and child (
i.e. when using [`child_process.fork()`][]), the `child.send()` method can be
used to send messages to the child process. When the child process is a Node.js
instance, these messages can be received via the `process.on('message')` event.
instance, these messages can be received via the [`process.on('message')`][] event.
For example, in the parent script:
@ -842,13 +842,13 @@ process.on('message', (m) => {
process.send({ foo: 'bar' });
```
Child Node.js processes will have a `process.send()` method of their own that
Child Node.js processes will have a [`process.send()`][] method of their own that
allows the child to send messages back to the parent.
There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages
containing a `NODE_` prefix in its `cmd` property are considered to be reserved
for use within Node.js core and will not be emitted in the child's
`process.on('message')` event. Rather, such messages are emitted using the
[`process.on('message')`][] event. Rather, such messages are emitted using the
`process.on('internalMessage')` event and are consumed internally by Node.js.
Applications should avoid using such messages or listening for
`'internalMessage'` events as it is subject to change without notice.
@ -856,7 +856,7 @@ Applications should avoid using such messages or listening for
The optional `sendHandle` argument that may be passed to `child.send()` is for
passing a TCP server or socket object to the child process. The child will
receive the object as the second argument passed to the callback function
registered on the `process.on('message')` event.
registered on the [`process.on('message')`][] event.
The `options` argument, if present, is an object used to parameterize the
sending of certain types of handles. `options` supports the following
@ -871,7 +871,7 @@ sent but before the child may have received it. The function is called with a
single argument: `null` on success, or an [`Error`][] object on failure.
If no `callback` function is provided and the message cannot be sent, an
`'error'` event will be emitted by the `ChildProcess` object. This can happen,
`'error'` event will be emitted by the [`ChildProcess`][] object. This can happen,
for instance, when the child process has already exited.
`child.send()` will return `false` if the channel has closed or when the
@ -914,8 +914,8 @@ can be handled by the parent and some by the child.
While the example above uses a server created using the `net` module, `dgram`
module servers use exactly the same workflow with the exceptions of listening on
a `'message'` event instead of `'connection'` and using `server.bind` instead of
`server.listen`. This is, however, currently only supported on UNIX platforms.
a `'message'` event instead of `'connection'` and using `server.bind()` instead of
`server.listen()`. This is, however, currently only supported on UNIX platforms.
#### Example: sending a socket object
@ -1050,23 +1050,36 @@ although there are only 4 characters:
console.log('中文测试');
```
[`popen(3)`]: http://linux.die.net/man/3/popen
[`ChildProcess`]: #child_process_child_process
[`'error'`]: #child_process_event_error
[`'exit'`]: #child_process_event_exit
[`'message'`]: #child_process_event_message
[`child.connected`]: #child_process_child_connected
[`child.disconnect()`]: #child_process_child_disconnect
[`child.kill()`]: #child_process_child_kill_signal
[`child.send()`]: #child_process_child_send_message_sendhandle_options_callback
[`child.stderr`]: #child_process_child_stderr
[`child.stdin`]: #child_process_child_stdin
[`child.stdout`]: #child_process_child_stdout
[`child_process.exec()`]: #child_process_child_process_exec_command_options_callback
[`child_process.execFile()`]: #child_process_child_process_execfile_file_args_options_callback
[`child_process.execFileSync()`]: #child_process_child_process_execfilesync_file_args_options
[`child_process.execSync()`]: #child_process_child_process_execsync_command_options
[`child_process.fork()`]: #child_process_child_process_fork_modulepath_args_options
[`child_process.spawn()`]: #child_process_child_process_spawn_command_args_options
[`child_process.spawnSync()`]: #child_process_child_process_spawnsync_command_args_options
[`ChildProcess#kill()`]: #child_process_child_kill_signal
[`ChildProcess#send()`]: #child_process_child_send_message_sendhandle_options_callback
[`ChildProcess`]: #child_process_child_process
[`Error`]: errors.html#errors_class_error
[`EventEmitter`]: events.html#events_class_eventemitter
[`EventEmitters`]: events.html#events_class_eventemitter
[`EventEmitter`]: events.html#events_class_events_eventemitter
[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
[`maxBuffer`]: #child_process_maxbuffer_and_unicode
[`net.Server`]: net.html#net_class_net_server
[`net.Socket`]: net.html#net_class_net_socket
[`options.detached`]: #child_process_options_detached
[`options.stdio`]: #child_process_options_stdio
[`process.disconnect()`]: process.html#process_process_disconnect
[`process.env`]: process.html#process_process_env
[`process.execPath`]: process.html#process_process_execpath
[`process.on('disconnect')`]: process.html#process_event_disconnect
[`process.on('message')`]: process.html#process_event_message
[`process.send()`]: process.html#process_process_send_message_sendhandle_callback
[`stdio`]: #child_process_options_stdio
[synchronous counterparts]: #child_process_synchronous_process_creation
[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
[`maxBuffer`]: #child_process_maxbuffer_and_unicode

60
doc/api/process.md

@ -16,6 +16,11 @@ continue.
as [`process.exit()`][] or uncaught exceptions, and should not be used as an
alternative to the `'exit'` event unless the intention is to schedule more work.
## Event: 'disconnect'
If process is spawned with an IPC channel, `'disconnect'` will be emitted when
IPC channel is closed. Read more in [child_process `'disconnect'` event][] doc.
## Event: 'exit'
Emitted when the process is about to exit. There is no way to prevent the
@ -52,7 +57,7 @@ event on the child's process object.
## Event: 'rejectionHandled'
Emitted whenever a Promise was rejected and an error handler was attached to it
(for example with `.catch()`) later than after an event loop turn. This event
(for example with [`promise.catch()`][]) later than after an event loop turn. This event
is emitted with the following arguments:
- `p` the promise that was previously emitted in an `'unhandledRejection'`
@ -140,7 +145,7 @@ down the process. It is not safe to resume normal operation after
Emitted whenever a `Promise` is rejected and no error handler is attached to
the promise within a turn of the event loop. When programming with promises
exceptions are encapsulated as rejected promises. Such promises can be caught
and handled using [`promise.catch(...)`][] and rejections are propagated through
and handled using [`promise.catch()`][] and rejections are propagated through
a promise chain. This event is useful for detecting and keeping track of
promises that were rejected whose rejections were not handled yet. This event
is emitted with the following arguments:
@ -182,7 +187,7 @@ var resource = new SomeResource();
In cases like this, you may not want to track the rejection as a developer
error like you would for other `'unhandledRejection'` events. To address
this, you can either attach a dummy `.catch(() => { })` handler to
this, you can either attach a dummy [`.catch(() => { })`][`promise.catch()`] handler to
`resource.loaded`, preventing the `'unhandledRejection'` event from being
emitted, or you can use the [`'rejectionHandled'`][] event.
@ -307,7 +312,7 @@ operations are pending. The following status codes are used in other
cases:
* `1` **Uncaught Fatal Exception** - There was an uncaught exception,
and it was not handled by a domain or an `'uncaughtException'` event
and it was not handled by a domain or an [`'uncaughtException'`][] event
handler.
* `2` - Unused (reserved by Bash for builtin misuse)
* `3` **Internal JavaScript Parse Error** - The JavaScript source code
@ -327,7 +332,7 @@ cases:
* `7` **Internal Exception Handler Run-Time Failure** - There was an
uncaught exception, and the internal fatal exception handler
function itself threw an error while attempting to handle it. This
can happen, for example, if a `process.on('uncaughtException')` or
can happen, for example, if a [`'uncaughtException'`][] or
`domain.on('error')` handler throws an error.
* `8` - Unused. In previous versions of Node.js, exit code 8 sometimes
indicated an uncaught exception.
@ -397,7 +402,7 @@ Note:
- `SIGSTOP` cannot have a listener installed.
Note that Windows does not support sending Signals, but Node.js offers some
emulation with `process.kill()`, and `child_process.kill()`. Sending signal `0`
emulation with [`process.kill()`][], and [`ChildProcess.kill()`][]. Sending signal `0`
can be used to test for the existence of a process. Sending `SIGINT`,
`SIGTERM`, and `SIGKILL` cause the unconditional termination of the target
process.
@ -495,9 +500,9 @@ the value of `process.config`.*
## process.connected
* {Boolean} Set to false after `process.disconnect()` is called
* {Boolean} Set to `false` after `process.disconnect()` is called
If `process.connected` is false, it is no longer possible to send messages.
If `process.connected` is `false`, it is no longer possible to send messages.
## process.cwd()
@ -665,7 +670,7 @@ emitMyWarning();
This is the set of Node.js-specific command line options from the
executable that started the process. These options do not show up in
`process.argv`, and do not include the Node.js executable, the name of
[`process.argv`][], and do not include the Node.js executable, the name of
the script, or any options following the script name. These options
are useful in order to spawn child processes with the same execution
environment as the parent.
@ -719,7 +724,7 @@ A number which will be the process exit code, when the process either
exits gracefully, or is exited via [`process.exit()`][] without specifying
a code.
Specifying a code to `process.exit(code)` will override any previous
Specifying a code to [`process.exit(code)`][`process.exit()`] will override any previous
setting of `process.exitCode`.
@ -837,7 +842,7 @@ console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
Send a signal to a process. `pid` is the process id and `signal` is the
string describing the signal to send. Signal names are strings like
`SIGINT` or `SIGHUP`. If omitted, the signal will be `SIGTERM`.
`'SIGINT'` or `'SIGHUP'`. If omitted, the signal will be `'SIGTERM'`.
See [Signal Events][] and kill(2) for more information.
Will throw an error if target does not exist, and as a special case, a signal
@ -869,11 +874,11 @@ Note: When SIGUSR1 is received by Node.js it starts the debugger, see
## process.mainModule
Alternate way to retrieve [`require.main`][]. The difference is that if the main
module changes at runtime, `require.main` might still refer to the original main
module changes at runtime, [`require.main`][] might still refer to the original main
module in modules that were required before the change occurred. Generally it's
safe to assume that the two refer to the same module.
As with `require.main`, it will be `undefined` if there was no entry script.
As with [`require.main`][], it will be `undefined` if there was no entry script.
## process.memoryUsage()
@ -1043,7 +1048,7 @@ relied upon to exist.
When Node.js is spawned with an IPC channel attached, it can send messages to its
parent process using `process.send()`. Each will be received as a
[`'message'`][] event on the parent's `ChildProcess` object.
[`'message'`][] event on the parent's [`ChildProcess`][] object.
*Note: this function uses [`JSON.stringify()`][] internally to serialize the `message`.*
@ -1055,7 +1060,7 @@ Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)
Sets the effective group identity of the process. (See setegid(2).)
This accepts either a numerical ID or a groupname string. If a groupname
This accepts either a numerical ID or a group name string. If a group name
is specified, this method blocks while resolving it to a numerical ID.
```js
@ -1099,7 +1104,7 @@ Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)
Sets the group identity of the process. (See setgid(2).) This accepts either
a numerical ID or a groupname string. If a groupname is specified, this method
a numerical ID or a group name string. If a group name is specified, this method
blocks while resolving it to a numerical ID.
```js
@ -1152,7 +1157,7 @@ if (process.getuid && process.setuid) {
A writable stream to stderr (on fd `2`).
`process.stderr` and `process.stdout` are unlike other streams in Node.js in
that they cannot be closed (`end()` will throw), they never emit the `finish`
that they cannot be closed ([`end()`][] will throw), they never emit the [`'finish'`][]
event and that writes can block when output is redirected to a file (although
disks are fast and operating systems normally employ write-back caching so it
should be a very rare occurrence indeed.)
@ -1202,7 +1207,7 @@ console.log = (msg) => {
```
`process.stderr` and `process.stdout` are unlike other streams in Node.js in
that they cannot be closed (`end()` will throw), they never emit the `'finish'`
that they cannot be closed ([`end()`][] will throw), they never emit the [`'finish'`][]
event and that writes can block when output is redirected to a file (although
disks are fast and operating systems normally employ write-back caching so it
should be a very rare occurrence indeed.)
@ -1287,21 +1292,30 @@ Will print something like:
openssl: '1.0.1k' }
```
[`'finish'`]: stream.html#stream_event_finish
[`'message'`]: child_process.html#child_process_event_message
[`'rejectionHandled'`]: #process_event_rejectionhandled
[`'uncaughtException'`]: #process_event_uncaughtexception
[`ChildProcess.disconnect()`]: child_process.html#child_process_child_disconnect
[`ChildProcess.kill()`]: child_process.html#child_process_child_kill_signal
[`ChildProcess.send()`]: child_process.html#child_process_child_send_message_sendhandle_options_callback
[`ChildProcess`]: child_process.html#child_process_class_childprocess
[`end()`]: stream.html#stream_writable_end_chunk_encoding_callback
[`Error`]: errors.html#errors_class_error
[`EventEmitter`]: events.html#events_class_eventemitter
[`EventEmitter`]: events.html#events_class_events_eventemitter
[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
[`net.Server`]: net.html#net_class_net_server
[`net.Socket`]: net.html#net_class_net_socket
[`process.argv`]: #process_process_argv
[`process.exit()`]: #process_process_exit_code
[`promise.catch(...)`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
[`'rejectionHandled'`]: #process_event_rejectionhandled
[`process.kill()`]: #process_process_kill_pid_signal
[`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
[`require.main`]: modules.html#modules_accessing_the_main_module
[`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_arg
[child_process `'disconnect'` event]: child_process.html#child_process_event_disconnect
[process_emit_warning]: #process_emitwarning_warning_name_ctor
[process_warning]: #process_event_warning
[Signal Events]: #process_signal_events
[Stream compatibility]: stream.html#stream_compatibility_with_older_node_js_versions
[the tty docs]: tty.html#tty_tty
[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
[process_warning]: #process_event_warning
[process_emit_warning]: #process_process_emitwarning_warning_name_ctor

Loading…
Cancel
Save