node.js - parent process kills child process, even though detached is set to true -


i confused , have been struggling find solution months. on osx.

i hear using child_process.spawn detached option set true, start child process leader of new process group , if parent exits, child process may continue running. however, never witnessed evidence of this.

https://nodejs.org/api/child_process.html

for example:

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

the above executed parent, , if 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 kill parent control-c, child process dies parent.

how can create background process independent of parent process node? killing me!

try including child.unref() method.

by default, parent wait detached child exit. prevent parent waiting given child, use child.unref() method. doing cause parent's event loop not include child in reference count, allowing parent exit independently of child, unless there established ipc channel between child , parent.

when using detached option start long-running process, process not stay running in background after parent exits unless provided stdio configuration not connected parent. if parent's stdio inherited, child remain attached controlling terminal.

example of long-running process, detaching , ignoring parent stdio file descriptors, in order ignore parent's termination:

example:

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

examples (from documentation):

const spawn = require('child_process').spawn;  const child = spawn(process.argv[0], ['child_program.js'], {   detached: true,   stdio: ['ignore'] });  child.unref(); 

alternatively 1 can redirect child process' output files:

const fs = require('fs'); const spawn = require('child_process').spawn; const out = fs.opensync('./out.log', 'a'); const err = fs.opensync('./out.log', 'a');  const child = spawn('prg', [], {  detached: true,  stdio: [ 'ignore', out, err ] });  child.unref(); 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -