为什么下面的程序不会在第二次 read
调用时阻塞?
int pid = fork();
if(pid) {
int fifo = open("testfifo", O_RDWR);
char buf[20];
while(1) {
read(fifo, buf, 10);
puts(buf);
}
} else {
int fifo = open("testfifo", O_WRONLY);
write(fifo, "teststring", 10);
close(fifo);
}
return 0;
第二个 read
调用继续返回 0
,即使 fifo 变空并且它应该阻塞 read
调用。
我错过了什么吗?
操作系统是 Windows,管道是用 mknod testfifo p
创建的。
最佳答案
我从另一个 stackoverflow 问题中发现,我应该每次都打开和关闭“服务器”管道,在本例中是父进程的管道;所以这是正确的代码:
int pid = fork();
if(pid) {
char buf[20];
while(1) {
int fifo = open("testfifo", O_RDWR);
read(fifo, buf, 15);
close(fifo);
puts(buf), fflush(stdout);
}
} else {
int fifo = open("testfifo", O_WRONLY);
write(fifo, "teststring", 15);
close(fifo);
}
关于c - FIFO 不会在读取时阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7256237/