1
我想运行node.js作为子进程并为其提供输入。使用C,这是我的一些示例代码。pipe不被子进程读取?
我遇到的问题是,虽然子进程的stdout仍然指向终端,但在给子进程标准输入打印'Hello World'行后,我什么都看不到。即使我()管道,我没有看到输出。但是,如果我关闭了管道的输入,那么终端上会出现'Hello World'。
子流程似乎只是缓冲 - 为什么? 我想最终将子进程stdout重定向到另一个管道,并从main()中读入 。
INT主(INT的argc,字符* 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; }
虽然[这个答案](http://stackoverflow.com/questions/1410849/bypassing-buffering-of-subprocess-output-with-popen-in-c-or-python)是指Python,它是一样的潜在问题。你必须以某种方式说服*其他程序*来减少缓冲。 (我不知道是否可以告诉node.js这么做,或者是否需要使用伪ttys。) – torek