我刚刚开始使用 UNIX FIFO,并且在试验我的第一个 FIFO 程序时发现了一些东西。该程序是这样工作的:创建 FIFO 后,使用 fork()
函数启动两个进程。子进程通过FIFO读取父亲传给他的东西,打印到屏幕上。交换的数据是指定为参数的字符串。问题是:在父部分,如果我忘记关闭 FIFO 的输入端(意味着我排除了 close(fd)
行)程序就会挂起,即使数据介于进程交换正确。否则,一切正常,程序终止而不会挂起。谁能解释一下为什么?
感谢您的耐心等待。这是主要功能的代码:
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("An argument must be specified\n");
return -1;
}
int ret = mkfifo("./fifo.txt", 0644);
char buf;
if(ret < 0)
{
perror("Error creating FIFO");
return -1;
}
pid_t pid = fork();
if(pid < 0)
{
perror("Error creating child process");
return -1;
}
if(pid == 0) /* child */
{
int fd = open("./fifo.txt", O_RDONLY); /* opens the fifo in reading mode */
while(read(fd, &buf, 1) > 0)
{
write(STDOUT_FILENO, &buf, 1);
}
write(STDOUT_FILENO, "\n", 1);
close(fd);
return 0;
}
else /* father */
{
int fd = open("./fifo.txt", O_WRONLY); /* opens the fifo in writing mode */
write(fd, argv[1], strlen(argv[1]));
close(fd);
waitpid(pid, NULL, 0);
return 0;
}
}
最佳答案
read(2)
阻塞,直到有可用的字符或 channel 在另一端关闭。父进程必须关闭管道,以便最后一个子进程 read()
返回。如果在父亲中省略 close(fd)
, child 将阻塞在 read()
中,直到父亲退出(自动关闭管道)但父亲会挂起waitpid()
直到 child 退出。
关于c - UNIX 先进先出 : the process hangs if I don't close the input side of the fifo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669609/