Alex Mills Alex Mills -5 years ago 170
Node.js Question

parent process kills child process, even though detached is set to true

I am really confused by this and have been struggling to find a solution for months. I am on OSX.

I hear that using child_process.spawn with the detached option set to true, will start the child process as a leader of a new process group and if the parent exits, the child process may continue running. However, I never witnessed any evidence of this.

For example:

const n = cp.spawn('node', ['watch-transpile.js'], {
detached: true,
stdio: ['ignore']

the above is executed by the parent, and if we run
$ ps aux | grep node

we get:

Olegzandr 2546 0.0 0.2 3048544 19564 ?? Ss 11:29PM 0:00.09 node lib/transpile/watch-transpile.js

Olegzandr 2541 0.0 0.7 3115684 60216 s000 S+ 11:29PM 0:01.47 node index -t -a -w

But when I kill the parent with control-c, the child process dies as well as the parent.

How can I truly create a background process that is independent of the parent process with node? this is killing me!

Answer Source

Aha! Of course. Those stupid Node docs!

This works.

        const n = cp.spawn('node', ['lib/transpile/watch-transpile.js'], {
            detached: true,
            stdio: ['ignore', 'ignore', 'ignore']

You explicitly ignore each stdio stream, not just using 'ignore' once; the docs don't mention this directly, but it makes sense given that the stdio property is an array.

See this issue on Github:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download