Run node as background process from script running as child process Run node as background process from script running as child process shell shell

Run node as background process from script running as child process


You need to set the detached option when you create the child process. This is sort of like nohup. See the documentation here: http://nodejs.org/api/child_process.html#child_process_options_detached

What this does is to make the child process the leader of a new "process group," so when the parent process group dies, the child can continue running.

Edit: the documentation says:

When using the detached option to start a long-running process, the process will not stay running in the background unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

So you must write code like this:

var child = spawn(cmd, args, {detached: true, stdio: ['ignore', 'ignore', 'ignore']});child.unref();

Or you can use their example to have stdout redirect to a file, etc.


When i spawned a process from a file that ran once, my child process had perfect behavior as parent file exited normally. Issue was raised as i was spawning process by a server file that was killed by Ctrl+c so it gave an error code on exit and as a result whole process group got SIGTERM which lead to killing of child process.

To successfully implement spawning i used double spawn i.e spawned a child process from my server file that further spawned child_process that ran my other node server. So i was able to avoid SIGTERM to reach grandchild and fulfill my requirement.