我刚刚开始使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
read(2)
阻止直到有可用字符或通道在另一端关闭.父进程必须关闭管道才能read()
返回最后一个子进程.如果省略close(fd)
父亲中的孩子,孩子将在read()
父亲退出之前阻止(自动关闭管道)但是父亲会waitpid()
一直等到孩子退出.