【问题标题】:Node.js write to child processNode.js 写入子进程
【发布时间】:2017-12-05 10:54:39
【问题描述】:

我正在尝试在 node.js 中使用 child_process 模块和树莓派上的 mpg123 播放器制作一个 mp3 网络广播。

问题来了: 当我尝试写入流时,我总是得到一个错误:

Error: write EPIPE
at exports._errnoException (util.js:1026:11)
at WriteWrap.afterWrite (net.js:795:14)

这是我尝试测试的内容:

//create a subprocess
var test = childProcess.exec('ls /home/pi/music');

//pipe all the output to the process output
test.stdout.pipe(process.stdout);
test.stderr.pipe(process.stderr);

test.stdin.setEncoding('utf-8');

//here I just want to write a key to the subprocess
test.stdin.write('q');
test.stdin.end()

任何人都知道,要做什么,创建的写入流在一切完成之前不会关闭?

当然,我仍然在 google 上搜索过这个:

Child_process throw an Error: write EPIPE

https://github.com/nodejs/node/issues/2985

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

https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback

请帮忙!

【问题讨论】:

  • ''ls /home/pi/music' 的子进程在您尝试在其输出上写入其他内容之前不会退出?
  • 我认为进程退出,这就是错误的原因。但我不知道如何stop 这个:c。如果它不停止,我认为它不会产生错误......
  • 不是因为你.end() stnd 流,而它已经在另一边结束了吗?
  • 你的意图是什么,如果你想测试你可以生成一个更大的输出来测试行为(比如说'dmesg')。你想播放mp3文件,为什么不配置播放器输出到stdout?

标签: javascript node.js child-process


【解决方案1】:

EPIPE 写入错误意味着有人正在写入一个没有人会读取的管道。

此外,由于此错误是在没有人处理它的上下文中引发的,因此该错误对您的进程来说是致命的。可悲的是,节点并不能很好地识别哪个流,但我们可以猜测它在您的代码中,并且此代码仅写入一个流...

如果您添加错误处理程序,您可以验证错误是否来自“stdin”流: test.stdin.on('error', (...args) => { console.log('stdin err', args); });

现在错误将被“处理”(很差),并且该过程将继续,因此您至少知道它来自哪里。

具体来说,这个test.stdin.write('q') 正在将q 写入您进程的标准输入。但是您的子进程是ls。它不接受标准输入上的任何内容,因此它关闭标准输入。因此,当父级尝试写入现已关闭的管道时,操作系统会发回 EPIPE 错误。所以,别再这样了。

您可能希望 ls 的行为与您交互式键入 ls 时的行为相同,但它可能不会(我怀疑您的交互式 ls 正在通过寻呼机,您希望您需要退出那个寻呼机?)这个子进程更相当于以交互方式运行/bin/ls

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2016-04-02
    • 1970-01-01
    相关资源
    最近更新 更多