0

So I have spawned one child process that I keep alive as long as the main process is alive. Since I use it very often I see no reason to kill it every few seconds.

How can I be sure to close the child process upon exiting the main one whether it crashed or not since if I don't it will become orphan. Also if I happen to get an orphan child what should I do?

John James
  • 587
  • 3
  • 8
  • 19
  • Possible duplicate of [doing a cleanup action just before node.js exits](https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits) – Artur P. Mar 18 '18 at 10:14

1 Answers1

2

You can use process on exit event:

process.on('exit', (code) => {
  // kill all workers
});

EDIT: I found more complex solution: https://stackoverflow.com/a/14032965/7526159

Artur P.
  • 886
  • 4
  • 12
  • That doesn't guarantee it will close upon any exit code. – John James Mar 18 '18 at 09:25
  • Since the workers will be draining resources its important to know I can kill them all upon exiting, so using a scenario where it might not kill them, is not the best case. Also I should mention I use a fork to spawn the childs, so am not 100% sure the parent doesn't kill them before existing, but upon searching thats what I came to understand. – John James Mar 18 '18 at 10:17
  • Ok. In child process we can listen on process.on('disconnect') event, and kill current process. https://nodejs.org/api/process.html#process_event_disconnect https://nodejs.org/api/child_process.html#child_process_event_disconnect – Artur P. Mar 18 '18 at 10:46