我遇到了管道問題。我正在嘗試執行例如ls | grep測試和我的程序凍結。我的程序是一個shell程序,我得到重定向和其他東西的工作,但我不能讓管道工作...我做錯了什麼?我有搜索答案,但無法找到任何解決我的問題。c中的管道問題
if(pipe(fd_pipe) < 0)
perror("pipe error...");
if ((pid = fork()) < 0) /* fork a child process */
{
perror("ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) /* the child process, do the first command */
{
printf("In first child...\n");
//dupPipe(fd_pipe, 1, STDOUT_FILENO); /* send to write end of pipe */
fflush(stdout);
std_out = dup(1); // for later restore...
close(fd_pipe[0]);
dup2(fd_pipe[1], 1);
printf("exec %s in first child...\n", comline[0].argv[0]);
if (execvp(comline[0].argv[0], comline[0].argv) < 0) /* execute the command */
{
fprintf(stderr,"-mish: Exe of %s failed...",comline[0].argv[0]);
fflush(stderr);
perror("");
}
}
else /* parent process*/
{
while (wait(&status) != pid) //wait for child to completion
;
fflush(stdin);
std_in = dup(0); // for later restore...
close(fd_pipe[1]);
dup2(fd_pipe[0], 0);
if (execvp(comline[1].argv[0], comline[1].argv) < 0) /* execute the command */
{
fprintf(stderr,"-mish: Exe of %s failed...",comline[0].argv[0]);
fflush(stderr);
perror("");
}
從技術上講,對'stdin'調用'fflush'是未定義的。如果你想要便攜,那麼不要這樣做。 –
「我有搜索答案」 - 更難搜索。 [你看到這個問題了嗎?](https://stackoverflow.com/questions/19356075/toy-shell-not-piping-correctly)? – WhozCraig
請注意,您不需要測試'execvp()'或其任何族的返回值。如果函數返回,則失敗;如果成功,它不會返回。您對'for later restore'的評論很奇怪;如果execvp()成功,則不會有'稍後'執行還原。如果命令執行失敗,則更清晰的評論將是'用於恢復',但如果您顯示代碼則更具說服力。 –