Skip to content

Instantly share code, notes, and snippets.

@mk-pmb
Created September 28, 2017 14:34
Show Gist options
  • Save mk-pmb/e48ded5215cf2f3fa54c5335aa68edd4 to your computer and use it in GitHub Desktop.
Save mk-pmb/e48ded5215cf2f3fa54c5335aa68edd4 to your computer and use it in GitHub Desktop.
Test for Node.js oneshot signal handlers https://github.com/nodejs/node/issues/15654
/*jslint indent: 2, maxlen: 80, node: true */
/* -*- tab-width: 2 -*- */
'use strict';
var EX = module.exports, fork = require('child_process').fork,
equal = require('assert').deepStrictEqual,
busyWait = true;
EX.main = function () {
var args = process.argv.slice(2);
if (args[0] === '--sig') { return EX.stubbornMode(args[1]); }
EX.testMode();
};
function noop() { return; }
EX.stubbornMode = function (sig) {
process.once('SIG' + sig, function () { console.log('Nope.'); });
setTimeout(noop, 1e9);
while (busyWait) { noop(); }
};
EX.testMode = function () {
var customSignal = 'INT', activeTimers = {}, signalsSent = [],
child = fork(module.filename, [ '--sig', customSignal ]);
if (!(child || false).pid) { throw new Error('Unable to fork'); }
child.spawnedAt = Date.now();
function killSoon(sig, delaySec) {
activeTimers[delaySec] = setTimeout(function () {
delete activeTimers[delaySec];
child.kill('SIG' + sig);
signalsSent.push(sig);
}, delaySec * 1000);
}
killSoon(customSignal, 0.2);
killSoon(customSignal, 0.4);
killSoon('KILL', 5);
function abandonTimers() {
Object.keys(activeTimers).forEach(function (timer) {
clearTimeout(activeTimers[timer]);
activeTimers[timer] = null;
});
}
child.once('close', abandonTimers);
function verifyTest(rv, sig) {
child.closedAt = Date.now();
equal(rv, null);
equal(sig, 'SIG' + customSignal);
equal(signalsSent, [ customSignal, customSignal ]);
var childDurationSec = (child.closedAt - child.spawnedAt) / 1000;
equal(Math.floor(childDurationSec), 0);
console.log('+OK test passed');
}
child.once('close', verifyTest);
};
if (require.main === module) { EX.main(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment