2013-10-30 78 views
2

在這個函數中,我該如何使它停止試圖從管道中讀取。即如果我運行命令ls | grep test grep不會輸出testtest.c,然後等待用戶輸入?管道閱讀器沒有看到EOF或EOS

pipe(pipefd); 

int pid = fork(); 
if (pid != 0) { 
    dup2(pipefd[0], STDIN_FILENO); 
    int rv2 = execv(get_contain_dir(command_to), args_to); 
    close(pipefd[0]); 
} else { 
    dup2(pipefd[1], STDOUT_FILENO); 
    int rv1 = execv(get_contain_dir(command_from), args_from); 
    close(pipefd[1]); 
} 
+0

你能更好地解釋你想達到什麼目的嗎?你希望父母的標準輸出重定向到孩子的標準輸入嗎? (你應該添加標籤linux) –

+1

我想模擬c中的控制檯管道。無論在父節點的輸出中執行的任何操作都通過管道輸入到子節點(通過STDOUT/STDIN)。上面的代碼運行良好,管道很好,但它似乎不想*關閉*管道。也就是說,在我原來的例子中「grep」之後,命令「保持打開」接受來自用戶的輸入。 正如我現在正在運行,它完全退出我的程序(這也是錯誤的)。 –

回答

2

您沒有正確關閉管道。每個過程必須關閉它不使用的管道:

int pid = fork(); 
if (pid != 0) { 
    dup2(pipefd[0], STDIN_FILENO); 
    close(pipefd[1]); // not using the left side 
    int rv2 = execv(get_contain_dir(command_to), args_to); 

} else { 
    dup2(pipefd[1], STDOUT_FILENO); 
    close(pipefd[0]); // not using the right side 
    int rv1 = execv(get_contain_dir(command_from), args_from); 
}