gpt4 book ai didi

c - 退出程序后输出执行UNIX命令

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:12 25 4
gpt4 key购买 nike

由于某些未知原因,当我在我的 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 of program when I enter "ls | sort -r" for example

在这个输出示例中,我使用“ls | sort -r”作为示例,另一个重要的注意事项是我的程序设计为仅处理一个管道,我不支持多管道命令。但是考虑到所有这些,我哪里出错了,我应该怎么做才能修复它以便它在 shell 内输出,而不是在 shell 外输出。非常感谢您提供的所有建议和帮助。

最佳答案

原因可能是您的父进程文件描述符尚未关闭。当您等待第二个命令终止时,它会挂起,因为写入端未关闭,因此它会等到写入端关闭或有新数据可供读取。

在等待进程终止之前尝试关闭 pipefd[0]pipefd[1]

另请注意,当一个进程终止时,wait(NULL); 将立即返回,如果您的进程在此之后仍在运行,您将需要第二个,以免生成僵尸。

关于c - 退出程序后输出执行UNIX命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58293804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com