Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatting revisions for child process doc #26141

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 97 additions & 92 deletions doc/api/child_process.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Child Process

<!--introduced_in=v0.10.0-->
<!--lint disable maximum-line-length-->

> Stability: 2 - Stable

Expand Down Expand Up @@ -41,20 +40,22 @@ 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()`][].*

* [`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
it spawns the command directly without first spawning a shell by default.
[`child_process.spawnSync()`][]. Each of these alternatives are implemented on
top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].

* [`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 it spawns the command directly without first spawning a shell by
default.
* [`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.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.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,
Expand All @@ -72,21 +73,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
allow for an optional `callback` function to be specified that is invoked
when the child process terminates.
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, macOS) [`child_process.execFile()`][] can be more efficient
because it does not spawn a shell by default. 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
the `.bat` or `.cmd` file as an argument (which is what the `shell` option and
[`child_process.execFile()`][] can vary based on platform. On Unix-type
operating systems (Unix, Linux, macOS) [`child_process.execFile()`][] can be
more efficient because it does not spawn a shell by default. 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 the `.bat` or
`.cmd` file as an argument (which is what the `shell` option and
[`child_process.exec()`][] do). In any case, if the script filename contains
spaces it needs to be quoted.

Expand Down Expand Up @@ -267,12 +269,13 @@ changes:
* Returns: {ChildProcess}

The `child_process.execFile()` function is similar to [`child_process.exec()`][]
except that it does not spawn a shell by default. Rather, the specified executable `file`
is spawned directly as a new process making it slightly more efficient than
[`child_process.exec()`][].
except that it does not spawn a shell by default. 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
spawned, behaviors such as I/O redirection and file globbing are not supported.
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
const { execFile } = require('child_process');
Expand Down Expand Up @@ -350,10 +353,10 @@ changes:

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
allows messages to be passed back and forth between the parent and child. See
[`subprocess.send()`][] for details.
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 [`subprocess.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
Expand Down Expand Up @@ -524,13 +527,13 @@ added: v0.7.10

On Windows, setting `options.detached` to `true` makes it possible for the
child process to continue running after the parent exits. The child will have
its own console window. *Once enabled for a child process, it cannot be
disabled*.
its own console window. Once enabled for a child process, it cannot be
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.
process will be made the leader of a new process group and session. Child
processes may continue running after the parent exits regardless of 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 `subprocess` to exit, use the
Expand Down Expand Up @@ -608,11 +611,12 @@ pipes between the parent and child. The value is one of the following:
for fds 0 - 2 are also available as [`subprocess.stdin`][],
[`subprocess.stdout`][] and [`subprocess.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 [`subprocess.send()`][]
method. If the child is a Node.js process, the presence of an IPC channel
will enable [`process.send()`][] and [`process.disconnect()`][] methods,
as well as [`'disconnect'`][] and [`'message'`][] events within the child.
between parent and child. A [`ChildProcess`][] may have at most one IPC
stdio file descriptor. Setting this option enables the
[`subprocess.send()`][] method. If the child is a Node.js process, the
presence of an IPC channel will enable [`process.send()`][] and
[`process.disconnect()`][] methods, as well as [`'disconnect'`][] and
[`'message'`][] events within the child.

Accessing the IPC channel fd in any way other than [`process.send()`][]
or using the IPC channel with a child process that is not a Node.js instance
Expand All @@ -628,9 +632,9 @@ pipes between the parent and child. The value is one of the following:
5. {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
have an underlying descriptor (file streams do not until the `'open'`
event has occurred).
corresponds to the index in the `stdio` array. The stream must have an
underlying descriptor (file streams do not until the `'open'` event has
occurred).
6. Positive integer - The integer value is interpreted as a file descriptor
that is currently open in the parent process. It is shared with the child
process, similar to how {Stream} objects can be shared.
Expand Down Expand Up @@ -670,9 +674,9 @@ 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 Node.js event loop, pausing execution of any additional code until the
spawned process exits.
[`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.

Blocking calls like these are mostly useful for simplifying general-purpose
scripting tasks and for simplifying the loading/processing of application
Expand Down Expand Up @@ -728,17 +732,17 @@ changes:
* Returns: {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
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.
[`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.

If the child process intercepts and handles the `SIGTERM` signal and
does not exit, the parent process will still wait until the child process has
exited.

If the process times out or has a non-zero exit code, this method ***will***
throw an [`Error`][] that will include the full result of the underlying
If the process times out or has a non-zero exit code, this method will throw an
[`Error`][] that will include the full result of the underlying
[`child_process.spawnSync()`][].

**If the `shell` option is enabled, do not pass unsanitized user input to this
Expand Down Expand Up @@ -791,15 +795,15 @@ changes:
* Returns: {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
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`
signal and doesn't exit, the parent process will wait until the child
process has exited.*

If the process times out or has a non-zero exit code, this method ***will***
throw. The [`Error`][] object will contain the entire result from
[`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. If the child process intercepts and handles the `SIGTERM`
signal and doesn't exit, the parent process will wait until the child process
has exited.

If the process times out or has a non-zero exit code, this method will throw.
The [`Error`][] object will contain the entire result from
[`child_process.spawnSync()`][].

**Never pass unsanitized user input to this function. Any input containing shell
Expand Down Expand Up @@ -872,9 +876,9 @@ The `child_process.spawnSync()` method is generally identical to
[`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
`SIGTERM` signal and doesn't exit, the parent process will wait until the child
process has exited.
completely exited. If the process intercepts and handles the `SIGTERM` signal
and doesn't exit, the parent process will wait until the child process has
exited.

**If the `shell` option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
Expand All @@ -885,8 +889,8 @@ arbitrary command execution.**
added: v2.2.0
-->

Instances of the `ChildProcess` class are [`EventEmitters`][`EventEmitter`] that represent
spawned child processes.
Instances of the `ChildProcess` class are [`EventEmitters`][`EventEmitter`] that
represent spawned child processes.

Instances of `ChildProcess` are not intended to be created directly. Rather,
use the [`child_process.spawn()`][], [`child_process.exec()`][],
Expand Down Expand Up @@ -945,13 +949,13 @@ exited, `code` is the final exit code of the process, otherwise `null`. If the
process terminated due to receipt of a signal, `signal` is the string name of
the signal, otherwise `null`. One of the two will always be non-null.

Note that when the `'exit'` event is triggered, child process stdio streams
might still be open.
When the `'exit'` event is triggered, child process stdio streams might still be
open.

Also, note that Node.js establishes signal handlers for `SIGINT` and
`SIGTERM` and Node.js processes will not terminate immediately due to receipt
of those signals. Rather, Node.js will perform a sequence of cleanup actions
and then will re-raise the handled signal.
Node.js establishes signal handlers for `SIGINT` and `SIGTERM` and Node.js
processes will not terminate immediately due to receipt of those signals.
Rather, Node.js will perform a sequence of cleanup actions and then will
re-raise the handled signal.

See waitpid(2).

Expand All @@ -964,8 +968,8 @@ added: v0.5.9
* `sendHandle` {Handle} A [`net.Socket`][] or [`net.Server`][] object, or
undefined.

The `'message'` event is triggered when a child process uses [`process.send()`][]
to send messages.
The `'message'` event is triggered when a child process uses
[`process.send()`][] to send messages.

The message goes through serialization and parsing. The resulting
message might not be the same as what is originally sent.
Expand Down Expand Up @@ -1006,7 +1010,7 @@ The `'disconnect'` event will be emitted when there are no messages in the
process of being received. This will most often be triggered immediately after
calling `subprocess.disconnect()`.

Note that when the child process is a Node.js instance (e.g. spawned using
When the child process is a Node.js instance (e.g. spawned using
[`child_process.fork()`]), the `process.disconnect()` method can be invoked
within the child process to close the IPC channel as well.

Expand Down Expand Up @@ -1034,14 +1038,14 @@ grep.on('close', (code, signal) => {
grep.kill('SIGHUP');
```

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
delivered to that process instead which can have unexpected results.
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 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.
While the function is called `kill`, the signal delivered to the child process
may not actually terminate the process.

See kill(2) for reference.

Expand Down Expand Up @@ -1180,8 +1184,8 @@ process.on('message', (m) => {
process.send({ foo: 'bar', baz: NaN });
```

Child Node.js processes will have a [`process.send()`][] method of their own that
allows the child to send messages back to the parent.
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. Messages
containing a `NODE_` prefix in the `cmd` property are reserved for use within
Expand All @@ -1202,8 +1206,8 @@ 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,
for instance, when the child process has already exited.
`'error'` event will be emitted by the [`ChildProcess`][] object. This can
happen, for instance, when the child process has already exited.

`subprocess.send()` will return `false` if the channel has closed or when the
backlog of unsent messages exceeds a threshold that makes it unwise to send
Expand Down Expand Up @@ -1245,8 +1249,9 @@ 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

Expand Down Expand Up @@ -1324,8 +1329,8 @@ added: v0.1.90

A `Writable Stream` that represents the child process's `stdin`.

*Note that if a child process waits to read all of its input, the child will not
continue until this stream has been closed via `end()`.*
If a child process waits to read all of its input, the child will not continue
until this stream has been closed via `end()`.

If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
then this will be `null`.
Expand All @@ -1342,8 +1347,8 @@ added: v0.7.10

A sparse array of pipes to the child process, corresponding with positions in
the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
to the value `'pipe'`. Note that `subprocess.stdio[0]`, `subprocess.stdio[1]`,
and `subprocess.stdio[2]` are also available as `subprocess.stdin`,
to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and
`subprocess.stdio[2]` are also available as `subprocess.stdin`,
`subprocess.stdout`, and `subprocess.stderr`, respectively.

In the following example, only the child's fd `1` (stdout) is configured as a
Expand Down