【问题标题】:Nodejs child process exit before stdio streams close在stdio流关闭之前Nodejs子进程退出
【发布时间】:2016-04-01 10:52:03
【问题描述】:

我刚刚对子进程进行了试验,并注意到退出事件在关闭事件之前触发 - 以下代码引发错误,因为 this._instance.stdin 不再存在(this._instance 已经为空)。

'use strict';

const spawn = require('child_process').spawn;

class Foo {
  constructor() {
    this._instance = null;
  }

  bar() {
    this._instance = spawn('ls', ['-l']);

    this._instance.on('close', (code, signal) => {
      this._instance.stdin.end();
    });

    this._instance.on('exit', (code, signal) => {
      this._instance = null;
    });

    return this._instance;
  }
}


var foo = new Foo();

console.log(foo.bar());

文档说明:

"请注意,当 'exit' 事件被触发时,子进程 stdio 流可能仍处于打开状态。"

我想知道这是怎么发生的,为什么进程退出后流仍然存在?它们是如何“关闭”的,这部分是由操作系统处理还是节点关闭剩余的 stdio 流?

实际上,我不一定会在退出时将 this._instance 设置为 null,因为这似乎不是一件好事,而且显然还为时过早。

【问题讨论】:

    标签: node.js unix child-process stdio


    【解决方案1】:

    close event 的文档揭示了为什么会发生这种情况。

    简而言之,stdio 可以被其他尚未退出的进程使用。

    我没有查看代码本身,但操作系统处理关闭 stdio 流的部分是有道理的。考虑将 stdio 管道传输到多个进程(使用 tee 管道可能是一个很好的例子)。

    在本例中,我怀疑您甚至不需要 end() 标准输入,因为 close 事件表明标准输入流已经关闭。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-30
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多