Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forwarding signals correctly to child process #269

Merged
merged 1 commit into from Jun 30, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 26 additions & 14 deletions src/index.ts
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