gpt4 book ai didi

c - FIFO 不会在读取时阻塞

转载 作者:可可西里 更新时间:2023-11-01 11:21:43 35 4
gpt4 key购买 nike

为什么下面的程序不会在第二次 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com