diff --git a/doc/api/process.md b/doc/api/process.md index 178928c8b6a321..755dfb537c93ed 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -350,6 +350,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). @@ -362,6 +365,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); ``` *Note*: An easy way to send the `SIGINT` signal is with `-C` in most diff --git a/lib/internal/process.js b/lib/internal/process.js index ff5ea58dda5f6c..56ff1f66397628 100644 --- a/lib/internal/process.js +++ b/lib/internal/process.js @@ -195,7 +195,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(() => {});