managed-tree.ts 784 B

123456789101112131415161718
  1. import { spawn } from 'node:child_process'
  2. import { rename, writeFile } from 'node:fs/promises'
  3. const [statePath] = process.argv.slice(2)
  4. if (statePath === undefined) throw new Error('usage: managed-tree.ts <state-path>')
  5. process.on('SIGTERM', () => {})
  6. process.on('SIGHUP', () => {})
  7. const descendant = spawn(process.execPath, [
  8. '-e',
  9. 'process.on("SIGTERM",()=>{});process.on("SIGHUP",()=>{});setInterval(()=>{},60_000)',
  10. ], { stdio: 'ignore' })
  11. if (descendant.pid === undefined) throw new Error('managed descendant did not publish a pid')
  12. const pendingStatePath = `${statePath}.pending-${process.pid}`
  13. await writeFile(pendingStatePath, JSON.stringify({ root: process.pid, descendant: descendant.pid }))
  14. await rename(pendingStatePath, statePath)
  15. setInterval(() => {}, 60_000)