Ответ 1
Скрипты сами несут ответственность за надлежащее завершение работы после прослушивания события SIGINT
, поскольку обработчик по умолчанию (убивающий процесс) отключен.
Посмотрите эту примерную программу:
process.on('SIGINT', function() {
console.log('SIGINT');
});
console.log('PID: ', process.pid);
var http = require('http'); // HTTP server to keep the script up long enough
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Выполните его, а затем попробуйте убить его: Он не будет работать. Сигнал SIGINT
всегда будет передан вашему обработчику сигнала настраиваемого построения. Чтобы правильно закрыть процесс, вам придется вручную вызвать process.exit()
:
process.on('SIGINT', function() {
console.log('SIGINT');
process.exit();
});
console.log('PID: ', process.pid);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
process.exit()
будет:
- Установите некоторые внутренние флаги
- Вызовите обработчики
process.on('exit')
- Вызов
process.reallyExit
- Какой вызовет функцию С++
exit()
, поэтомуprocess.exit()
является окончательным и вызовет выключение (если вы не заблокируете выполнение бесконечным циклом в вашем обработчикеon('exit')
).
Короче говоря: ваш код, вероятно, где-то слушает SIGINT
. Вы можете получить список этих слушателей через:
var listeners = process.listeners('SIGINT');
Вы даже можете распечатать их на консоли:
for (var i = 0; i < listeners.length; i++) {
console.log(listeners[i].toString());
}
Используя приведенную выше информацию, вы можете легко скомпилировать еще один SIGINT
-handler, который будет перечислять все обработчики, а затем чисто выйти из процесса, надеясь, что ваш путь к непослушным:
process.on('SIGINT', function() {
console.log('Nice SIGINT-handler');
var listeners = process.listeners('SIGINT');
for (var i = 0; i < listeners.length; i++) {
console.log(listeners[i].toString());
}
process.exit();
});
Полная программа для тестирования:
process.on('SIGINT', function() {
console.log('Naughty SIGINT-handler');
});
process.on('exit', function () {
console.log('exit');
});
console.log('PID: ', process.pid);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
process.on('SIGINT', function() {
console.log('Nice SIGINT-handler');
var listeners = process.listeners('SIGINT');
for (var i = 0; i < listeners.length; i++) {
console.log(listeners[i].toString());
}
process.exit();
});