Description
- Version: v9.2.1
- Platform: Linux ip-172-31-29-251 3.13.0-135-generic lib: micro-optimize url.resolve() #184-Ubuntu SMP Wed Oct 18 11:55:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
- Subsystem: child_process
child_process.spawn()
supports an option detached
which "makes it possible for the child process to continue running after the parent exits." child_process.fork()
does not officially support detached
as one of its options (by "officially support", I mean that it is not documented as a valid option); but I think it should be officially supported.
My reasons:
- It works today. (details below)
- It's useful. (details below)
- I can't think of any reason that it shouldn't be supported.
If you agree, then no code changes would be required, but the documentation for child_process.fork()
would need to list detached
as a valid option. (Also, TypeScript's @types/node
would need to be updated, but that would probably be a separate GitHub issue somewhere else.)
1. It works today: First of all, if you look at the current source for child_process.fork()
, it's clear (and not surprising) that fork()
is just a simple wrapper around spawn()
. It passes most options through unchanged.
To prove that detached
works with fork()
: save this as demo.js:
// launch with "node demo.js" or "node demo.js detached"
const child_process = require('child_process')
if (process.argv.indexOf('--daemon') === -1) {
let options = {};
if (process.argv.indexOf('detached') >= 0) {
options.detached = true;
}
const child = child_process.fork(__filename, ['--daemon'], options);
console.log('hello from parent; press ^C to terminate parent')
process.stdin.read()
} else {
console.log(`hello from child, my pid is ${process.pid}`)
setInterval(() => {}, 5000)
}
To see the NON-detached behavior, launch it with node demo.js
. It will call fork()
, so there are now two instances running. Then press ^C; if you do ps aux | grep demo.js
you will see that both instances terminated.
To see the detached behavior, repeat the above but with node demo.js detached
. In this case, after ^C, the child process is still running.
2. It's useful: child_process.fork()
can be useful for starting daemon processes, and detached
is certainly useful for daemons.