Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS child processes being killed when parent dies

I am using child_process.spawn() to start a script from my Node.JS application running on Ubuntu. As far as I know, standard forked or spawned *nix processes don't generally die when the parent dies, but when spawning processes from Node.JS, they seem to get killed when my application crashes, or is aborted with ctrl-c etc.

Why is this and is there a way around this? I can't seem to find any obvious option in the child_process API.

My application starts some quite long-running tasks that should run in the background, and if my node server crashes or is restarted for some other reason I don't want to interrupt the tasks, instead I want the node server to come back up and gracefully resume monitoring the progress of those running tasks.

like image 916
JHH Avatar asked Jun 08 '15 12:06

JHH


People also ask

What happens to child process when parent is killed?

Orphan Processes When a parent process dies before a child process, the kernel knows that it's not going to get a wait call, so instead it makes these processes "orphans" and puts them under the care of init (remember mother of all processes).

How do you kill child processes that spawn their own child processes in node JS?

var spawn = require('child_process'). spawn; var child = spawn('my-command', {detached: true}); process. kill(-child. pid);

What happens to the Childs If you kill a parent process in Linux?

Killing the parent does not generally kill the child. SIGKILL is unignorable. The only reason it might block is if a system call is hung and the process is stuck in kernel mode.

How does Nodejs handle child process?

Usually, Node. js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.


1 Answers

you need to set the detached option

If the detached option is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits.

var child = spawn('prg', [], {
   detached: true,
   stdio: [ 'ignore', out, err ]
 });
like image 129
Johny Avatar answered Oct 05 '22 09:10

Johny