【问题标题】:Redirect stdout/stderr from a child_process to /dev/null or something similar将 stdout/stderr 从 child_process 重定向到 /dev/null 或类似的东西
【发布时间】:2016-02-05 04:34:16
【问题描述】:

我正在使用 Node.js (require('child_process')) 创建一些 child_processes,并且我想确保每个 child_process 的 stdout/stderr 不会进入终端,因为我只想记录父进程的输出.有没有办法将 child_processes 中的 stdout/stderr 流重定向到 /dev/null 或其他不是终端的地方?

https://nodejs.org/api/child_process.html

也许只是:

var n = cp.fork('child.js',[],{
   stdio: ['ignore','ignore','ignore']
});

我刚试过,好像没用。

现在我尝试了这个:

var stdout, stderr;

if (os.platform() === 'win32') {
    stdout = fs.openSync('NUL', 'a');
    stderr = fs.openSync('NUL', 'a');
}
else {
    stdout = fs.openSync('/dev/null', 'a');
    stderr = fs.openSync('/dev/null', 'a');
}

然后这个选项:

stdio: ['ignore',  stdout, stderr],

但这并没有做到,但似乎使用“detached:true”选项可能会成功。

【问题讨论】:

  • 在你的分叉进程中劫持process.stdout.write 怎么样?
  • 不幸的是我不能覆盖它,child_process 必须有办法做到这一点!
  • 我想我实际上可以覆盖它,但是通过 child_process 调用这样做有好处
  • 在文档中,stdio 选项似乎适用于 spawn,而不是 fork,也许您想要 silent 选项?
  • @mzulch 我认为静音选项可能是一个

标签: node.js stdout stderr child-process


【解决方案1】:

解决方案:

丢弃分叉子进程的stdoutstderr

  1. 设置pipe,即在分叉时使用silent = True

  2. 并将父进程上的stdoutstderr 管道重定向到/dev/null


解释:

node.js documentation states

为方便起见,options.stdio 可能是以下字符串之一:

'pipe' - equivalent to ['pipe', 'pipe', 'pipe'] (the default)
'ignore' - equivalent to ['ignore', 'ignore', 'ignore']
'inherit' - equivalent to [process.stdin, process.stdout, process.stderr] or [0,1,2]

显然childprocess.fork()不支持ignore;只有childprocess.spawn() 可以。

fork 确实支持silent 选项,允许在pipeinherit 之间进行选择。

分叉子进程时:
如果silent = True,则 stdio = pipe
如果silent = False,那么 stdio = inherit

silent
布尔值

如果为 true,则子节点的 stdin、stdout 和 stderr 将通过管道传递给父节点,否则将从父节点继承。

有关详细信息,请参阅 child_process.spawn() 的 stdio 的“管道”和“继承”选项。

【讨论】:

  • 感谢这个答案很好,我不久前投了赞成票...我目前想知道是否有办法将 child_process 的 stderr/stdout 直接通过管道传输到文件而不是返回到父进程然后到文件。有什么想法吗?
  • 我猜只是在 child_process 中调用 process.stderr.pipe()
猜你喜欢
  • 2018-02-25
  • 2011-05-14
  • 2019-10-11
  • 2012-01-23
  • 2014-07-22
  • 1970-01-01
  • 2017-11-30
  • 2022-01-18
  • 2012-08-07
相关资源
最近更新 更多