如何解决孩子不读取另一个孩子的输出,将其放入管道
我一直在完成这项学校作业,而且我非常接近完成。
任务是在 C 中创建一个 bash shell,这听起来很基本,但它必须支持管道、IO 重定向和管道命令中的标志。除了一件事外,我一切都在工作; |管道子进程没有获得用户命令进程子进程写入管道的任何数据。如果我要删除 pipechild 的子叉,并将 if(pipe_cmd[0] != '\0') 中的所有内容作为父级运行,它会工作得很好(减去由于 execlp 而结束程序)。如果我在管道部分中使用 printf(),输出将在正确的文件或终端中,这只会让来自用户命令进程子进程的输入无法到达需要作为罪魁祸首的地方。
有人看到我如何使用管道的问题吗?考虑到管道的定义,这一切对我来说都是 100% 正常的。
int a[2];
pipe(a);
//assume file_name is something like file.txt
strcat(file_name,"file.txt");
strcat(pipe_cmd,"wc");
if(!fork())
{
if(pipe_cmd[0] != '\0') // if there's a pipe
{
close(1); //close normal stdout
dup(a[1]); // making stdout same as a[1]
close(a[0]); // closing other end of pipe
execlp("ls","ls",NULL);
}
else if(file_name[0] != '\0') // if just a bare command with a file redirect
{
int rootcmd_file = open(file_name,O_APPEND|O_WRONLY|O_CREAT,0644);
dup2(rootcmd_file,STDOUT_FILENO);
execlp("ls",NULL); // writes ls to the filename
}
// if no pipe or file name write...
else if(rootcmd_flags[0] != '\0') execlp("ls",NULL)
else execlp("ls",NULL);
} else wait(0);
if(pipe_cmd[0] != '\0') // parent goes here,if pipe.
{
pipechild = fork();
if(pipechild != 0) // *PROBLEM ARISES HERE- IF THIS IS FORKED,IT WILL HAVE NO INFO TAKEN IN.
{
close(0); // closing normal stdin
dup(a[0]); // making our input come from the child above
close(a[1]); // close other end of pipe
if(file_name[0] != '\0') // if a filename does exist,we must reroute the output to the pipe
{
close(1); // close normal stdout
int fileredir_pipe = open(file_name,0644);
dup2(fileredir_pipe,STDOUT_FILENO); //redirects STDOUT to file
execlp("wc","wc",NULL); // this outputs nothing
}
else
{
// else there is no file.
// executing the pipe in stdout using execlp.
execlp("wc",NULL); // this outputs nothing
}
}
else wait(0);
}
提前致谢。对于某些代码被保留,我深表歉意。这仍然是一项积极的任务,我不希望出现任何学术不诚实的情况。这篇文章已经够冒险了。
解决方法
} else wait(0);
显示的代码 fork
是第一个子进程,然后 wait
使其在此时终止。
第一个子进程在其标准输出上设置了一个管道。管道将连接到第二个子进程的标准输入。这个方案的致命缺陷是第二个子进程还没有启动,直到第一个进程终止才会启动。
管道具有有限的内部缓冲。如果第一个进程产生很少的输出,那么它的输出将适合微小的管道缓冲区,它会写入它的输出,然后安静地终止,没有更明智的。
但如果管道缓冲区已满,进程将阻塞并等待,直到有东西从管道中读取并清除它。只要它发生,它就会等待。等等,等等,等等。而且由于第二个子进程还没有启动,父进程在等待第一个进程终止,它会一直等待,白白等待。
由于这个原因,这个整体逻辑存在致命缺陷。正确的逻辑是完全fork
并执行所有子进程,关闭父进程中的管道描述符(这个也很重要),然后{{1 }} 用于终止所有 子进程。 wait
必须是这里发生的最后一件事,否则事情会以各种惊人而神秘的方式破裂。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。