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.
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).
var spawn = require('child_process'). spawn; var child = spawn('my-command', {detached: true}); process. kill(-child. pid);
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.
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.
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 ]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With