【问题标题】:pipe not being read by subprocess?管道没有被子进程读取?
【发布时间】:2013-07-12 19:09:42
【问题描述】:

我想将 node.js 作为子进程运行并为其提供输入。使用 C,这是我的一些示例代码。

我遇到的问题是,虽然子进程的标准输出仍被定向到终端,但在给子进程标准输入提供 print 'Hello World' 行后,我什么也看不到。即使我 fflush() 管道,我也看不到任何输出。但是,如果我关闭管道的输入,终端上会出现“Hello World”。

子进程似乎只是缓冲 - 这是为什么呢? 我想最终将子进程标准输出重定向到另一个管道并读取它 来自 main()。

int main(int argc, char* argv[]) {

  int toNode[2];

  pipe(toNode);

  pid_t child_pid = fork();
  if (child_pid == 0) { // child

      // close write end
      close(toNode[1]);
      // connect read end to stdin
      dup2(toNode[0], STDIN_FILENO);


      // run node executable
      char* arg_list[] = { "/usr/bin/node", NULL};
      execvp(arg_list[0], arg_list);

      fprintf(stderr, "process failed to start: %s\n", strerror(errno));
      abort();
   }
   else { // parent

      FILE* stream;

      // close read end
      close(toNode[0]);

      // convert write fd to FILE object
      stream = fdopen(toNode[1], "w");

      fprintf(stream, "console.log('Hello World');\n");
      fflush(stream);

      //close(toNode[1]);


      waitpid(child_pid, NULL, 0);

   }

return 0;   }

【问题讨论】:

  • 虽然this answer 指的是Python,但它是同一个潜在问题。您必须以某种方式说服 其他程序 减少缓冲。 (我不知道是否可以告诉 node.js 这样做,或者您是否需要使用伪 tty。)

标签: c linux node.js process pipe


【解决方案1】:

正在读取的管道没有问题。问题是/usr/bin/node 默认情况下,如果它检测到stdin 是交互式的,它只会调用REPL(读取-评估-打印循环)。如果您有足够新的nodejs 版本,那么您可以提供-i--interactive 命令行标志,但这不仅仅是在读取每一行时执行它;它还可以真正充当控制台,包括将 ANSI 颜色序列插入输出并打印每个表达式的值。

请参阅此forum thread 了解更多信息。

【讨论】:

    猜你喜欢
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多