我有一个通过 EAGI 与 Asterisk 通信的程序。 Asterisk 打开我的 Node.js 应用程序并通过 STDIN 向其发送数据,程序通过 STDOUT 发送 Asterisk 命令。当用户挂断电话时,Node.js 进程会收到一个 SIGHUP 命令。这是为了更干净的退出而被拦截。此功能正在运行。
Asterisk 还在 fd 3 (STDERR+1) 上发送 RAW 音频数据。 Node.js 进程会正确拦截数据,并能够读取音频、转换音频或执行任何其他需要完成的操作。但是,当在 fd 3 上创建 createReadStream 时,Node.js 进程不会退出并很快变成僵尸。如果我注释掉 createReadStream 代码,Node.js 会按预期退出。
如何让 Node.js 像预期的那样使用 process.exit() 函数退出?我使用的是 Node.js 版本 v0.10.30。
Node.js createReadStream 代码:
// It was success
this.audioInStream = fs.createReadStream( null, { 'fd' : 3 } );
// Pipe the audio stream to a blackhole for now so it doesn't get queued up
this.audioInStream.pipe( blackhole() );
SIGHUP 代码:
process
.on( 'SIGHUP', function() {
log.message.info( "[%s] Asterisk process hung up.", that.callerid );
that.exitWhenReady();
} );
exitWhenReady 函数
Index.prototype.exitWhenReady = function() {
if( !this.canExit )
return;
log.message.info( "[%s] Exiting program successfully.", this.callerid );
// Get rid of our streams
this.audioInStream.unpipe();
this.audioInStream.close();
this.audioInStream.destroy();
process.exit( 0 );
};
黑洞模块:
var inherits = require( 'util' ).inherits;
var Writable = require( 'stream' ).Writable;
var process = require( 'process' );
function Blackhole( opts ) {
if( !(this instanceof Blackhole) )
return( new Blackhole( opts ) );
if( !opts )
opts = {};
Writable.call( this, opts );
}
inherits( Blackhole, Writable );
Blackhole.prototype._write = function( chunk, encoding, done ) {
process.nextTick( done );
};
module.exports = Blackhole;
值得注意的是
Asterisk process hung up
和
Exiting program successfully.
当 createReadStream 正在读取 fd 3 时,永远不会出现在日志文件中,但当它不是时,它们就会出现。
最佳答案
我发现 Hook SIGHUP 并打开 fd 3 会导致程序即使在调用 process.exit() 时也不会关闭。这真的很奇怪。
我为解决此问题所做的工作是监听进程的“退出”事件。在“退出”事件中,我用 SIGTERM 手动终止了自己的进程。这足以停止整个程序。我发现这实际上与 Winston 记录器异常记录器一起工作得很好。 Winston 能够将异常写入日志文件,然后成功退出。
结果代码:
process
.on( 'SIGHUP', function() {
log.message.info( "[%s] Asterisk process hung up.", that.callerid );
that.exitWhenReady( true );
} )
.on( 'exit', function() {
process.kill( process.pid, 'SIGTERM' );
} );
上述函数基本上是在发送 SIGHUP 时调用 exitWhenReady()。检查所有任务是否完成,一旦所有任务完成,它将调用“process.exit()”,调用上述事件的函数。
我希望这对某些人有帮助。
关于javascript - Node.js process.exit() 不会在 createReadStream 打开时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30853218/