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