简体   繁体   English

中断从FIFO频道读取的while循环

[英]Break a while loop that reads from fifo channel

I have to simulate the shell behavior within a C program in UNIX, having in mind one important thing: the parent process receives all the commands and sends them to the child. 考虑到一件重要的事情,我必须在UNIX中的C程序中模拟shell行为:父进程接收所有命令并将它们发送给子进程。 The child then executes the command received, and then sends the output to the father. 然后,孩子执行接收到的命令,然后将输出发送给父亲。 The idea is that I received the command from the parent and my primary child fork() so that his own child can execvp the command and send the output to the fifo pipe. 我的想法是我从父级和主要子级fork()那里收到命令,以便他自己的子级可以执行该命令并将输出发送到fifo管道。 The problem is I cannot break the while loop(which prints the correct output): 问题是我无法打破while循环(打印正确的输出):

mkfifo("output",S_IFIFO|0644);
while(read(fifod2,&c,1))
      printf("%c",c);

I realise the fifo is of variable size, but the second child must have sent an EOF when terminated, so that when the read reaches it, returns 0. But that doesn't seem to happen. 我意识到fifo的大小是可变的,但是第二个子项在终止时必须发送了EOF,以便在读取达到该值时返回0。但这似乎没有发生。 Ask me for more portions of code, if needed. 如果需要,请询问我更多的代码部分。 Thank you 谢谢

Because the parent opened its end of the fifo with O_RDWR , there is a process with a writable file descriptor to the fifo at all times. 由于父对象使用O_RDWR打开了fifo的末尾,因此始终有一个向fifo写入文件描述符的进程。 The EOF only occurs when there are no writable fds to the fifo, and so since the parent process is keeping such a writable fd open, it'll never get an EOF. EOF仅在fifo没有可写fds时发生,因此,由于父进程将这种可写fd保持打开状态,因此永远不会获得EOF。

Try opening with O_RDONLY in the parent instead. 尝试用父O_RDONLY中的O_RDONLY打开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM