Skip to content

Commit

Permalink
Merge pull request #269 from anthonyalayo/aalayo-fix/graceful-shutdown
Browse files Browse the repository at this point in the history
Forwarding signals correctly to child process
  • Loading branch information
wclr authored Jun 30, 2021
2 parents 5b2e4d8 + a629f35 commit 534de06
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { makeLog } from './log'
const version = require('../package.json').version
const tsNodeVersion = require('ts-node').VERSION
const tsVersion = require('typescript').version
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']

export const runDev = (
script: string,
Expand Down Expand Up @@ -118,6 +119,7 @@ export const runDev = (
child = fork(cmd[0], cmd.slice(1), {
cwd: process.cwd(),
env: process.env,
detached: true,
})

starting = false
Expand Down Expand Up @@ -167,11 +169,15 @@ export const runDev = (
compiler.compile(message)
})

child.on('exit', function (code) {
log.debug('Child exited with code %s', code)
if (!child) return
if (!child.respawn) process.exit(code || 0)
child = undefined
child.on('close', (code: number, signal: string) => {
log.debug('Child closed with code %s', code)
if (signal) {
log.debug(`Exiting process with signal ${signal}`)
process.kill(process.pid, signal)
} else {
log.debug(`Exiting process with code ${code}`)
process.exit(code)
}
})

if (cfg.respawn) {
Expand Down Expand Up @@ -203,14 +209,14 @@ export const runDev = (
})
compiler.writeReadyFile()
}
const killChild = () => {
const killChild = (signal: NodeJS.Signals) => {
if (!child) return
log.debug('Sending SIGTERM kill to child pid', child.pid)
log.debug(`Sending ${signal} to child pid`, child.pid)
if (opts['tree-kill']) {
log.debug('Using tree-kill')
kill(child.pid)
} else {
child.kill('SIGTERM')
child.kill(signal)
}
}
function stop(willTerminate?: boolean) {
Expand All @@ -223,8 +229,8 @@ export const runDev = (
log.debug('Disconnecting from child')
child.disconnect()
if (!willTerminate) {
killChild()
}
killChild('SIGTERM')
}
}

Expand Down Expand Up @@ -261,11 +267,17 @@ export const runDev = (
}
}

// Relay SIGTERM
process.on('SIGTERM', function () {
log.debug('Process got SIGTERM')
killChild()
process.exit(0)
signals.forEach((signal: NodeJS.Signals) =>
process.on(signal, () => {
log.debug(`Process got ${signal}, killing child`)
killChild(signal)
})
)

process.on('exit', () => {
if(child) {
child.kill()
}
})

const compiler = makeCompiler(opts, {
Expand Down

0 comments on commit 534de06

Please sign in to comment.