简体   繁体   English

阅读fifo:为什么阻止然后非阻止

[英]read fifo: why is it blocking then non-blocking

I'm using FIFO to make two processes communicate. 我正在使用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);


The server will first block there to wait for some messages in fifoName . 服务器将首先在fifoName阻止以等待fifoName某些消息。 When some messages are coming (the client is executed), the server reads them and then the loop will finish. 当一些消息到来(客户端已执行)时,服务器将读取它们,然后循环将结束。

I'm confused now. 我现在很困惑。 Because I can't figure out why the first time that the server calls read and it blocks there whereas when it calls read again and it doesn't block anymore. 因为我无法弄清楚为什么服务器第一次调用read会阻塞,而在再次调用read时却不再阻塞。

I print the return value of read and I get 0 after receiving the first message. 我打印read的返回值,并在收到第一条消息后得到0。

What I need is to make the read blocking each time so that the server can receive any message as soon as some client sends messages. 我需要的是每次都阻止read以使服务器可以在某些客户端发送消息后立即接收任何消息。

You got 0 as an indicator there is no more data left and there will be no more data as the other side of the pipe got closed. 您得到0作为指标,因为管道的另一端被关闭,所以没有剩余数据,也没有更多数据。

I presume you want the server to stick around and handle multiple clients, possibly even at the same time. 我假设您希望服务器能够坚持住并处理多个客户端,甚至可能同时进行。

Pipes are fundamentally unsuitable for this purpose. 管道根本上不适合该目的。 You want to use unix sockets instead. 您想改用unix套接字

Finally, loops like this one: 最后,像这样的循环:

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

are fundamentally wrong. 从根本上讲是错误的。 it is very easy to get an error from read due to signal arrival. 由于信号到来,很容易从读取中获取错误。

Also note you violate DRY by repeating the '100' for the buffer size as opposed to eg using sizeof(msg). 还要注意,对于缓冲区大小重复使用“ 100”,而不是使用sizeof(msg),这违反了DRY。

you can simply retry the read. 您可以简单地重试读取。 For example 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM