watchdog.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. // this spawns a child process that listens for SIGHUP when the
  3. // parent process exits, and after 200ms, sends a SIGKILL to the
  4. // child, in case it did not terminate.
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.watchdog = void 0;
  7. const child_process_1 = require("child_process");
  8. const watchdogCode = String.raw `
  9. const pid = parseInt(process.argv[1], 10)
  10. process.title = 'node (foreground-child watchdog pid=' + pid + ')'
  11. if (!isNaN(pid)) {
  12. let barked = false
  13. // keepalive
  14. const interval = setInterval(() => {}, 60000)
  15. const bark = () => {
  16. clearInterval(interval)
  17. if (barked) return
  18. barked = true
  19. process.removeListener('SIGHUP', bark)
  20. setTimeout(() => {
  21. try {
  22. process.kill(pid, 'SIGKILL')
  23. setTimeout(() => process.exit(), 200)
  24. } catch (_) {}
  25. }, 500)
  26. })
  27. process.on('SIGHUP', bark)
  28. }
  29. `;
  30. /**
  31. * Pass in a ChildProcess, and this will spawn a watchdog process that
  32. * will make sure it exits if the parent does, thus preventing any
  33. * dangling detached zombie processes.
  34. *
  35. * If the child ends before the parent, then the watchdog will terminate.
  36. */
  37. const watchdog = (child) => {
  38. let dogExited = false;
  39. const dog = (0, child_process_1.spawn)(process.execPath, ['-e', watchdogCode, String(child.pid)], {
  40. stdio: 'ignore',
  41. });
  42. dog.on('exit', () => (dogExited = true));
  43. child.on('exit', () => {
  44. if (!dogExited)
  45. dog.kill('SIGKILL');
  46. });
  47. return dog;
  48. };
  49. exports.watchdog = watchdog;
  50. //# sourceMappingURL=watchdog.js.map