[英]read fifo: why is it blocking then non-blocking
我正在使用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
阻止以等待fifoName
某些消息。 当一些消息到来(客户端已执行)时,服务器将读取它们,然后循环将结束。
我现在很困惑。 因为我无法弄清楚为什么服务器第一次调用read
会阻塞,而在再次调用read
时却不再阻塞。
我打印read
的返回值,并在收到第一条消息后得到0。
我需要的是每次都阻止read
以使服务器可以在某些客户端发送消息后立即接收任何消息。
您得到0作为指标,因为管道的另一端被关闭,所以没有剩余数据,也没有更多数据。
我假设您希望服务器能够坚持住并处理多个客户端,甚至可能同时进行。
管道根本上不适合该目的。 您想改用unix套接字 。
最后,像这样的循环:
while(read(fd, msg, 100) > 0)
{
std::cout<<"msg received: "<<msg<<std::endl;
}
从根本上讲是错误的。 由于信号到来,很容易从读取中获取错误。
还要注意,对于缓冲区大小重复使用“ 100”,而不是使用sizeof(msg),这违反了DRY。
您可以简单地重试读取。 例如
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.