Nodejs – 进程在退出时挂起(Ctrl + C)

我有一个node.js项目,它做许多事情,它产生subprocess,它打开一个http和socket.io服务器等。

当我从控制台运行它,用Ctrl+Cclosures它,它只是挂起。 从webstorm中,停止这个过程是一个两步的过程,首先我停下来,然后我需要再次点击button,只有第二次button是一个骷髅图标。

现在,我知道这样会留下一些开放或悬挂的东西,但我无法弄清楚什么,我试图追踪所有开始进程的地方,并确保我正确地杀死它们。

有没有一种方法来debugging,并找出是什么让我的过程挂起? 难道它是日志logging,打开一个写入stream,永远不会closures? 我甚至不知道什么样的事情会使信号在SIGINT上挂起。

编辑:我已经下载pstree ,看看是否有任何的主进程生成的subprocess保持活着。 看起来他们都正常终止 – 主节点进程是唯一剩下的。

一旦他们侦听到SIGINT事件,脚本本身就负责正确closures,因为默认处理程序(终止进程)被禁用。

看看这个例子程序:

 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信号将始终传递给您的自定义构build信号处理程序。 为了正确地closures进程,您将不得不手动调用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()会:

  1. 设置一些内部标志
  2. 调用 process.on('exit')处理程序
  3. 调用process.reallyExit
  4. 这将调用 C ++的exit()函数,因此process.exit()final的,并且会导致closures(除非你在on('exit')处理函数中阻止了无限循环的执行)。

长话短说:您的代码可能在某处侦听SIGINT 。 您可以通过以下方式获取这些侦听器的列表:

 var listeners = process.listeners('SIGINT'); 

你甚至可以在控制台上打印它们:

 for (var i = 0; i < listeners.length; i++) { console.log(listeners[i].toString()); } 

使用上面提供的信息,您可以轻松地编译另一个SIGINT处理程序,它将列出所有处理程序,然后干净地退出该过程,并希望将您的path引导至顽皮的path:

 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(); }); 

完整的testing程序:

 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(); });