Skip to content

Commit 534de06

Browse files
authored
Merge pull request #269 from anthonyalayo/aalayo-fix/graceful-shutdown
Forwarding signals correctly to child process
2 parents 5b2e4d8 + a629f35 commit 534de06

File tree

1 file changed

+26
-14
lines changed

1 file changed

+26
-14
lines changed

src/index.ts

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { makeLog } from './log'
1616
const version = require('../package.json').version
1717
const tsNodeVersion = require('ts-node').VERSION
1818
const tsVersion = require('typescript').version
19+
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']
1920

2021
export const runDev = (
2122
script: string,
@@ -118,6 +119,7 @@ export const runDev = (
118119
child = fork(cmd[0], cmd.slice(1), {
119120
cwd: process.cwd(),
120121
env: process.env,
122+
detached: true,
121123
})
122124

123125
starting = false
@@ -167,11 +169,15 @@ export const runDev = (
167169
compiler.compile(message)
168170
})
169171

170-
child.on('exit', function (code) {
171-
log.debug('Child exited with code %s', code)
172-
if (!child) return
173-
if (!child.respawn) process.exit(code || 0)
174-
child = undefined
172+
child.on('close', (code: number, signal: string) => {
173+
log.debug('Child closed with code %s', code)
174+
if (signal) {
175+
log.debug(`Exiting process with signal ${signal}`)
176+
process.kill(process.pid, signal)
177+
} else {
178+
log.debug(`Exiting process with code ${code}`)
179+
process.exit(code)
180+
}
175181
})
176182

177183
if (cfg.respawn) {
@@ -203,14 +209,14 @@ export const runDev = (
203209
})
204210
compiler.writeReadyFile()
205211
}
206-
const killChild = () => {
212+
const killChild = (signal: NodeJS.Signals) => {
207213
if (!child) return
208-
log.debug('Sending SIGTERM kill to child pid', child.pid)
214+
log.debug(`Sending ${signal} to child pid`, child.pid)
209215
if (opts['tree-kill']) {
210216
log.debug('Using tree-kill')
211217
kill(child.pid)
212218
} else {
213-
child.kill('SIGTERM')
219+
child.kill(signal)
214220
}
215221
}
216222
function stop(willTerminate?: boolean) {
@@ -223,8 +229,8 @@ export const runDev = (
223229
log.debug('Disconnecting from child')
224230
child.disconnect()
225231
if (!willTerminate) {
226-
killChild()
227232
}
233+
killChild('SIGTERM')
228234
}
229235
}
230236

@@ -261,11 +267,17 @@ export const runDev = (
261267
}
262268
}
263269

264-
// Relay SIGTERM
265-
process.on('SIGTERM', function () {
266-
log.debug('Process got SIGTERM')
267-
killChild()
268-
process.exit(0)
270+
signals.forEach((signal: NodeJS.Signals) =>
271+
process.on(signal, () => {
272+
log.debug(`Process got ${signal}, killing child`)
273+
killChild(signal)
274+
})
275+
)
276+
277+
process.on('exit', () => {
278+
if(child) {
279+
child.kill()
280+
}
269281
})
270282

271283
const compiler = makeCompiler(opts, {

0 commit comments

Comments
 (0)