FIFO 在读取时不会阻塞 [英] FIFO doesn't block on read

查看:37
本文介绍了FIFO 在读取时不会阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

第二个read 调用继续返回0,即使fifo 变为空并且它应该阻塞read 调用.

The second read call continues returning 0 even though the fifo become empty and it should block on the read call.

我错过了什么吗?

操作系统是 Windows,管道是用 mknod testfifo p 创建的.

The OS is Windows and the pipe has been created with a mknod testfifo p.

推荐答案

我从另一个 stackoverflow 问题中发现,我应该每次打开和关闭服务器"管道,在这种情况下是父进程的管道;所以这是正确的代码:

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);
}

这篇关于FIFO 在读取时不会阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆