[英]Execution of UNIX command is being outputted after I exit the program
由于某些未知原因,当我在 shell 程序中执行管道命令时,它们仅在我退出程序后才输出,有人知道为什么吗?
代码:
int execCmdsPiped(char **cmds, char **pipedCmds){
// 0 is read end, 1 is write end
int pipefd[2];
pid_t pid1, pid2;
if (pipe(pipefd) == -1) {
fprintf(stderr,"Pipe failed");
return 1;
}
pid1 = fork();
if (pid1 < 0) {
fprintf(stderr, "Fork Failure");
}
if (pid1 == 0) {
// Child 1 executing..
// It only needs to write at the write end
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
if (execvp(pipedCmds[0], pipedCmds) < 0) {
printf("\nCouldn't execute command 1: %s\n", *pipedCmds);
exit(0);
}
} else {
// Parent executing
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork Failure");
exit(0);
}
// Child 2 executing..
// It only needs to read at the read end
if (pid2 == 0) {
close(pipefd[1]);
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
if (execvp(cmds[0], cmds) < 0) {
//printf("\nCouldn't execute command 2...");
printf("\nCouldn't execute command 2: %s\n", *cmds);
exit(0);
}
} else {
// parent executing, waiting for two children
wait(NULL);
}
}
}
Output:
在这个 output 的示例中,我使用了“ls | sort -r”作为示例,另一个重要注意事项是我的程序设计为仅处理一个 pipe,我不支持多管道命令。 但是考虑到所有这些,我哪里出错了,我应该怎么做才能修复它,以便它在 shell 内输出,而不是在它之外。 非常感谢您提供的任何和所有建议和帮助。
原因是您的父进程文件描述符尚未关闭。 当您等待第二个命令终止时,它会挂起,因为写入端未关闭,因此它会等到写入端关闭或有新数据可供读取。
在等待进程终止之前尝试关闭pipefd[0]
和pipefd[1]
。
还要注意wait(NULL);
当一个进程终止时将立即返回,如果您的进程在此之后仍然运行,您将需要第二个以不生成僵尸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.