Search code examples
node.jsprocesschild-processdetachbackground-foreground

node.js: How to spawn detached child in foreground and exit


According to the docs for child_process.spawn I would expect to be able to run a child process in the foreground and allow the node process itself to exit like so:

handoff-exec.js:

'use strict';

var spawn = require('child_process').spawn;

// this console.log before the spawn seems to cause
// the child to exit immediately, but putting it
// afterwards seems to not affect it.
//console.log('hello');

var child = spawn(
  'ping'
, [ '-c', '3', 'google.com' ]
, { detached: true, stdio: 'inherit' }
);

child.unref();

Instead of seeing the output of the ping command, it simply exits without any message or error.

node handoff-exec.js
hello
echo $?
0

So... is it possible in node.js (or at all) to run a child in the foreground as the parent exits?

Buggy Node Versions

I found that removing console.log('hello'); allows the child to run, however, it still doesn't pass foreground stdin control to the child. That's obviously not intended, therefore something must be buggy in the version of node I was using at the time...

https://github.com/nodejs/node/issues/5549


Solution

  • Solution

    The code in the question was actually correct. There was a legitimate bug in node at the time.

    'use strict';
    
    var spawn = require('child_process').spawn;
    
    console.log("Node says hello. Let's see what ping has to say...");
    
    var child = spawn(
      'ping'
    , [ '-c', '3', 'google.com' ]
    , { detached: true, stdio: 'inherit' }
    );
    
    child.unref();
    

    The snippet above will run effectively the same as if it had been backgrounded by the shell:

    ping -c 3 google.com &