2

I am looking for a way to kill all child processes spawned when my parent process die (including by receiving SIGKILL).

PM2 process manager seems to have the key, because sending a SIGKILL to pm2 Daemon causes all child processes to exit (on Linux platform).

So do you know how PM2 achieve this ? how can I reproduce this behavior ?

Thanks !

Teajo
  • 21
  • 1
  • 3

1 Answers1

1
'use strict'

const { fork } = require('child_process')

// fork a child process
const child = fork('new_process.js')

// when the main process exits, send the kill signal to the child process
process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`)
  child.kill(9)
})

Usefull docs

NodeJS - Child Process - kill()

NodeJS - Process - exit event

Andrea Franchini
  • 548
  • 4
  • 14