Node.js process.exit() 不会在 createReadStream 打开时退出

2024-02-21

我有一个通过 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() );

信号代码:

process
.on( 'SIGHUP', function() {
    log.message.info( "[%s] Asterisk process hung up.", that.callerid );
    that.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;

值得注意的是

星号进程挂起

And

成功退出程序。

当 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' );
} );

上面的函数基本上在发送 SIGHUP 时调用 exitWhenReady()。它会检查所有任务是否已完成,一旦所有任务完成,它将调用“process.exit()”,该函数会调用上述事件的函数。

我希望这对某人有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Node.js process.exit() 不会在 createReadStream 打开时退出 的相关文章

随机推荐