signal-manager.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const runningProcs = new Set()
  2. let handlersInstalled = false
  3. // NOTE: these signals aren't actually forwarded anywhere. they're trapped and
  4. // ignored until all child processes have exited. in our next breaking change
  5. // we should rename this
  6. const forwardedSignals = [
  7. 'SIGINT',
  8. 'SIGTERM',
  9. ]
  10. // no-op, this is so receiving the signal doesn't cause us to exit immediately
  11. // instead, we exit after all children have exited when we re-send the signal
  12. // to ourselves. see the catch handler at the bottom of run-script-pkg.js
  13. // istanbul ignore next - this function does nothing
  14. const handleSignal = () => {}
  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. }