55

I have an endless NodeJS script.js loop and I need this script to execute another script in background as a service which is a WebSocket service actually.

var exec = require('child_process').exec; exec('node bgService.js &'); 

So now both scripts are running okay!

When I do a Ctrl+C on my script.js, the bgService.js script is also removed from memory which I don't want to.

How to run something in the background and forget ?

2 Answers 2

95

You can do it using child_process.spawn with detached option:

var spawn = require('child_process').spawn; spawn('node', ['bgService.js'], { detached: true }); 

It will make child process the leader of a new process group, so it'll continue running after parent process will exit.

But by default parent process will wait for the detached child to exit, and it'll also listen for its stdio. To completely detach child process from the parent you should:

  • detach child's stdio from the parent process, piping it to some file or to /dev/null
  • remove child process from the parent event loop reference count using unref() method

Here is an example of doing it:

var spawn = require('child_process').spawn; spawn('node', ['bgService.js'], { stdio: 'ignore', // piping all stdio to /dev/null detached: true }).unref(); 

If you don't want to loose child's stdin output, you may pipe it to some log file:

var fs = require('fs'), spawn = require('child_process').spawn, out = fs.openSync('./out.log', 'a'), err = fs.openSync('./out.log', 'a'); spawn('node', ['bgService.js'], { stdio: [ 'ignore', out, err ], // piping stdout and stderr to out.log detached: true }).unref(); 

For more information see child_process.spawn documentation

Sign up to request clarification or add additional context in comments.

6 Comments

Is it possible to write the process id to a file?
@chovy sure. spawn returns an instance of ChildProcess class, containing, among other things, pid. of a spawned process
fs.writeFileSync(pidFile, `${ff.pid}\n`, 'utf8');
@chovy yes, that's the idea. But please, don't use ES6 syntax in non-ES6 questions, since it may confuse people.
fs.writeFileSync(pidFile, ff.pid+'\n', 'utf8'); es5
|
6

Short answer: (tl;dr)

spawn('command', ['arg', ...], { stdio: 'ignore', detached: true }).unref() 

unref is required to prevent parent from waiting.

docs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.