From 5a696ec535f244d3bb118fd4d49bff41711778e6 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Mon, 22 Sep 2014 14:35:11 -0700 Subject: [PATCH] better signal handling. --- example/index.js | 2 +- lib/bitcoind.js | 45 +++++++++++++++++++++++---------------------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/example/index.js b/example/index.js index cdd2f68d..7997a746 100755 --- a/example/index.js +++ b/example/index.js @@ -17,7 +17,7 @@ bitcoind.start(function(err) { setTimeout(function() { (function next(hash) { return bitcoind.getBlock(hash, function(err, block) { - if (err) return console.log(err.message); + if (err) return print(err.message); print(block); if (block.tx.length && block.tx[0].txid) { var txid = block.tx[0].txid; diff --git a/lib/bitcoind.js b/lib/bitcoind.js index efdbec21..a72017aa 100644 --- a/lib/bitcoind.js +++ b/lib/bitcoind.js @@ -32,32 +32,26 @@ Bitcoin.prototype.start = function(callback) { var self = this; var none = {}; + var isSignal = {}; + var sigint = { name: 'SIGINT', signal: isSignal }; + var sighup = { name: 'SIGHUP', signal: isSignal }; + var sigquit = { name: 'SIGQUIT', signal: isSignal }; var exitCaught = none; var errorCaught = none; this.log_pipe = bitcoindjs.start(function(err, status) { - process.on('SIGINT', function() { - if (process.listeners('SIGINT').length > 1) { - return; - } - if (!self._shutdown) { - process.exit(0); - } else { - self.stop(); - exitCaught = 0; - } - }); - - process.on('SIGHUP', function() { - if (process.listeners('SIGHUP').length > 1) { - return; - } - if (!self._shutdown) { - process.exit(0); - } else { - self.stop(); - exitCaught = 0; - } + [sigint, sighup, sigquit].forEach(function(signal) { + process.on(signal.name, signal.listener = function() { + if (process.listeners(signal.name).length > 1) { + return; + } + if (!self._shutdown) { + process.exit(0); + } else { + self.stop(); + exitCaught = signal; + } + }); }); var exit = process.exit; @@ -115,6 +109,13 @@ Bitcoin.prototype.start = function(callback) { delete self._shutdown; if (exitCaught !== none) { + if (exitCaught.signal === isSignal) { + process.removeListener(exitCaught.name, exitCaught.listener); + setImmediate(function() { + process.kill(process.pid, exitCaught.name); + }); + return; + } return self._exit(exitCaught); }