signal-manager.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const runningProcs = new Set()
  2. let handlersInstalled = false
  3. const forwardedSignals = [
  4. 'SIGINT',
  5. 'SIGTERM',
  6. ]
  7. // no-op, this is so receiving the signal doesn't cause us to exit immediately
  8. // instead, we exit after all children have exited when we re-send the signal
  9. // to ourselves. see the catch handler at the bottom of run-script-pkg.js
  10. const handleSignal = signal => {
  11. for (const proc of runningProcs) {
  12. proc.kill(signal)
  13. }
  14. }
  15. const setupListeners = () => {
  16. for (const signal of forwardedSignals) {
  17. process.on(signal, handleSignal)
  18. }
  19. handlersInstalled = true
  20. }
  21. const cleanupListeners = () => {
  22. if (runningProcs.size === 0) {
  23. for (const signal of forwardedSignals) {
  24. process.removeListener(signal, handleSignal)
  25. }
  26. handlersInstalled = false
  27. }
  28. }
  29. const add = proc => {
  30. runningProcs.add(proc)
  31. if (!handlersInstalled) {
  32. setupListeners()
  33. }
  34. proc.once('exit', () => {
  35. runningProcs.delete(proc)
  36. cleanupListeners()
  37. })
  38. }
  39. module.exports = {
  40. add,
  41. handleSignal,
  42. forwardedSignals,
  43. }