Mik*_*tti 4 javascript stream exit node.js
我有一个程序通过EAGI与Asterisk通信.Asterisk打开我的Node.js应用程序并通过STDIN发送数据,程序通过STDOUT发送Asterisk命令.当用户挂断时,Node.js进程会收到一个SIGHUP命令.这是为了清洁退出而截获的.此功能正常运行.
Asterisk还在fd 3(STDERR + 1)上发送RAW音频数据.Node.js进程正确拦截数据,并能够读取音频,转换它或其他任何需要完成的事情.但是,当在fd 3上创建createReadStream时,Node.js进程将不会退出并迅速成为Zombie.如果我注释掉createReadStream代码,Node.js将按预期退出.
如何使用process.exit()函数让Node.js退出?我正在使用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() );
Run Code Online (Sandbox Code Playgroud)
SIGHUP代码:
process
.on( 'SIGHUP', function() {
log.message.info( "[%s] Asterisk process hung up.", that.callerid );
that.exitWhenReady();
} );
Run Code Online (Sandbox Code Playgroud)
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 );
};
Run Code Online (Sandbox Code Playgroud)
黑洞模块:
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;
Run Code Online (Sandbox Code Playgroud)
值得注意的是
星号处理挂断了
和
成功退出程序.
当createReadStream正在读取fd 3时,从不在日志文件中显示,但是当它不是这样时.
我发现钩住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' );
} );
Run Code Online (Sandbox Code Playgroud)
上面的函数在发送SIGHUP时基本上调用exitWhenReady().检查所有任务是否完成,一旦所有任务完成,它将调用"process.exit()",它调用上述事件的函数.
我希望这有助于某人.