阅读FIFO:为什么会阻止然后进行非阻滞
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
中的一些消息。当某些消息到来(执行客户端)时,服务器会读取它们,然后循环完成。
我现在很困惑。因为我无法弄清楚服务器第一次调用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);
相关文章:
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么 ComPtr 的函数返回不同的值,然后 &?
- 为什么要在结构中放置枚举,然后使用 typedef 名称?
- 为什么部分初始化一个类然后调用委托 ctor 失败?
- 为什么我不能定义一元运算符,然后在 MSVC 的模板类中声明具有相同名称的友元二进制运算符?
- 不明白为什么这个简单的递归开始工作然后崩溃
- 为什么下面的使用链表实现线性队列的代码返回垃圾值然后崩溃
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 为什么没有std :: Future ::然后在C 17中
- 当我递增指针然后将其删除时,为什么我的程序会崩溃
- 阅读FIFO:为什么会阻止然后进行非阻滞
- 为什么在打印东西时没有保留顺序,先用cerr,然后用cout
- 为什么将 int a=1 移到左 31 位然后向右移 31 位,它变成 -1
- 为什么会这样?堆,展示了一件事,然后又展示了另一件事
- 为什么我的变量从1到2,然后又回到1
- 为什么在多个 cpp 文件中包含相同的标头,然后它们的编译工作
- 为什么 clang++ 警告内联enable_if然后无法链接
- 为什么一旦我将引用声明为 const 然后它可以采用不同类型的数据?
- C++字符串。为什么答案显示字符串"狗"大于"猫",然后"猫"大于"狗"?
- 为什么一个C程序编译并链接到一个C编译器,然后在运行时SIGILL