From f56a4ba11a0181e93e196e56aadd0ac8a33aec1b Mon Sep 17 00:00:00 2001 From: Robert Rossmann Date: Mon, 25 Sep 2017 11:28:00 +0200 Subject: [PATCH] process: Send signal name to signal handlers PR-URL: https://github.com/nodejs/node/pull/15606 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis Reviewed-By: Evan Lucas Reviewed-By: Gireesh Punathil Reviewed-By: Bartosz Sosnowski --- doc/api/process.md | 11 +++++++++++ lib/internal/process.js | 2 +- test/parallel/test-signal-args.js | 24 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-signal-args.js diff --git a/doc/api/process.md b/doc/api/process.md index 574fc933671d14..74d9fb0cc1532e 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -349,6 +349,9 @@ Signal events will be emitted when the Node.js process receives a signal. Please refer to signal(7) for a listing of standard POSIX signal names such as `SIGINT`, `SIGHUP`, etc. +The signal handler will receive the signal's name (`'SIGINT'`, + `'SIGTERM'`, etc.) as the first argument. + The name of each event will be the uppercase common name for the signal (e.g. `'SIGINT'` for `SIGINT` signals). @@ -361,6 +364,14 @@ process.stdin.resume(); process.on('SIGINT', () => { console.log('Received SIGINT. Press Control-D to exit.'); }); + +// Using a single function to handle multiple signals +function handle(signal) { + console.log(`Received ${signal}`); +} + +process.on('SIGINT', handle); +process.on('SIGTERM', handle); ``` * `SIGUSR1` is reserved by Node.js to start the [debugger][]. It's possible to diff --git a/lib/internal/process.js b/lib/internal/process.js index 4573b9429ed0cd..1d1ed5cd977f51 100644 --- a/lib/internal/process.js +++ b/lib/internal/process.js @@ -201,7 +201,7 @@ function setupSignalHandlers() { wrap.unref(); - wrap.onsignal = function() { process.emit(type); }; + wrap.onsignal = function() { process.emit(type, type); }; const signum = constants[type]; const err = wrap.start(signum); diff --git a/test/parallel/test-signal-args.js b/test/parallel/test-signal-args.js new file mode 100644 index 00000000000000..d9fa6df347ddaa --- /dev/null +++ b/test/parallel/test-signal-args.js @@ -0,0 +1,24 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); + +if (common.isWindows) { + common.skip('Sending signals with process.kill is not supported on Windows'); +} + +process.once('SIGINT', common.mustCall((signal) => { + assert.strictEqual(signal, 'SIGINT'); +})); + +process.kill(process.pid, 'SIGINT'); + +process.once('SIGTERM', common.mustCall((signal) => { + assert.strictEqual(signal, 'SIGTERM'); +})); + +process.kill(process.pid, 'SIGTERM'); + +// Prevent Node.js from exiting due to empty event loop before signal handlers +// are fired +setImmediate(() => {});