node.js spawned process sticks around if script is killed
Asked Answered
A

1

12

Is it possible to make sure that processes spawned with node.js child_process will be killed when the parent is killed?

Here's an example script

var spawn = require('child_process').spawn;
var log_tail = spawn("tail", ["-f", "/dev/null"]);

setInterval(function() {
  console.log('just chilling');
}, 10000);

If I look at the process tree I see this:

$ ps faux
ubuntu    9788  0.0  0.0  73352  1840 ?        S    15:04   0:00  |   \_ sshd: ubuntu@pts/7  
ubuntu    9789  0.0  0.2  25400  6804 pts/7    Ss   15:04   0:00  |       \_ -bash
ubuntu   10149  1.0  0.2 655636  8696 pts/7    Sl+  15:07   0:00  |           \_ node test.js
ubuntu   10151  0.0  0.0   7184   608 pts/7    S+   15:07   0:00  |               \_ tail -f /dev/null

Then later I need to stop that script and can't ctrl-c (say my ssh connection is lost)

$ kill 10149
$ ps faux
ubuntu   10151  0.0  0.0   7184   608 pts/7    S    15:07   0:00 tail -f /dev/null

You can see that the tail process is still running and has become detached from any parent.

Is there a programatic way to kill a spawned process if the spawner is killed?

Is there an option I can pass to spawn or should I use a different method or do I need to catch the kill signal (and will that work for a kill -9)?

Acquisitive answered 9/8, 2012 at 21:12 Comment(2)
My problem is just the opposite. Spawned processes are not kept alive if the parent dies, and that's what I want.Holp
Update: seems to happen only on Windows.Holp
S
16

Not very labor friendly, but this serves as the template I use:

var spawn = require("child_process").spawn;
var workers = [];

var killWorkers = function() {
  workers.forEach(function(worker) {
    process.kill(worker);
  });
});

process.on("uncaughtException", killWorkers);
process.on("SIGINT", killWorkers);
process.on("SIGTERM", killWorkers);

var new_worker = spawn("tail", ["-f", "/dev/null"]);
workers.push(new_worker);

I primarily use this for killing workers in a cluster when the master process dies. Ed: Obviously, you could just call killWorkers from anywhere, not just crashes or interrupts.

Skeptical answered 9/8, 2012 at 21:20 Comment(2)
note that kill -9 will still leave the workers around. For my use case that's probably ok, but bewareAcquisitive
Right. kill -9 won't actually even fire the process's exit event; not sure how you'd catch it inside of node in that case.Skeptical

© 2022 - 2024 — McMap. All rights reserved.