阅读FIFO:为什么会阻止然后进行非阻滞

read fifo: why is it blocking then non-blocking

本文关键字:然后 为什么 阅读 FIFO      更新时间:2023-10-16

我正在使用FIFO进行两个过程进行交流。

//client:
const char * msg = "Hello, I'm cleint1.";
const char * fifoName = "../server/fifo.tmp";
int fd = open(fifoName, O_WRONLY);
write(fd, msg, strlen(msg) + 1);
close(fd);

//server:
char msg[100];
const char * fifoName = "fifo.tmp";
mkfifo(fifoName, 0666);
int fd = open(fifoName, O_RDONLY);
while(read(fd, msg, 100) > 0)
{
    std::cout<<"msg received: "<<msg<<std::endl;
}
close(fd);
unlink(fifoName);


服务器将首先阻止那里等待fifoName中的一些消息。当某些消息到来(执行客户端)时,服务器会读取它们,然后循环完成。

我现在很困惑。因为我无法弄清楚服务器第一次调用read的原因,而它再次在此封锁,而当它再次调用read并且它不再阻止。

我打印read的返回值,收到第一个消息后获得0。

我需要的是使read每次阻止,以便在某些客户发送消息后立即接收任何消息。

您得到0作为指示器,没有更多的数据,并且由于管道的另一侧关闭,将不再有数据。

我想您希望服务器坚持下去并处理多个客户,甚至可能同时。

管道从根本上不适合此目的。您要使用 UNIX插座而不是。

最后,像这样的循环:

while(read(fd, msg, 100) > 0)
{
    std::cout<<"msg received: "<<msg<<std::endl;
}

从根本上是错误的。由于信号到达,从读取中获取错误非常容易。

还要注意,通过重复缓冲尺寸而不是例如使用sizeof(msg)。

您可以简单地重试读取。例如

int iResult;
do
{
    iResult = read(fd, buffer, size);
    if (0 == iResult)
    {
           // Skip to the end of the do loop
            continue;
    }
        // Handle real errors
} while (!condition);