gpt4 book ai didi

c - 管道没有被子进程读取?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:20 26 4
gpt4 key购买 nike

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

我遇到的问题是,虽然子进程的标准输出仍然定向到终端,但在向子进程标准输入输入打印“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; }

最佳答案

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

查看此 forum thread获取更多信息。

关于c - 管道没有被子进程读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17645446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com