FIFO doesn't block on read
Why the following program doesn't block on the second read
call?
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;
The second read
call continues returning 0
even though the fifo become empty and it should block on the read
call.
Am I missing something?
The OS is Windows and the pipe has been created with a mknod testfifo p
.
I found, from another stackoverflow question, that i should open and close the "server" pipe, in this case the pipe of the parent process, each time; so here's the correct code:
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);
}
You did not close the file
EDIT: deleted something embarrassing.
精彩评论