【问题标题】:Read/write from/to FIFO从/向FIFO读/写
【发布时间】:2023-03-04 21:54:02
【问题描述】:

我一直在尝试实现fifo读写,场景是这样的,writer1向fifo写入4个字节,reader1读取其中的2个字节,reader2读取接下来的2个字节,下面是我所做的,

作家.c

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
int main()
{
FILE *file;
unsigned char message[] = {0x66,0x66,0x67,0x67};
file = fopen("fifo1","wb");
fwrite(&message, 1,4,file);
}

reader.c

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
int main()
{
FILE *file;
unsigned char buff[2];
file = fopen("fifo1","rb");
fread(&buff, 1,2,file);

printf("%c\n",buff[0]);printf("%c\n",buff[1]);
}

然后我同时遵守了它们,并在第一个终端上运行 reader1,在第二个终端上运行 reader2,在第三个终端上运行 writer。

我以为我会在其中一个阅读器中获取前两个字节 (ff),在另一个阅读器中获取后两个字节 (gg),但它并没有像我想象的那样工作,有人可以让我知道我做错了什么,请注意我不关心谁读取了前两个字节或后两个字节,这里重要的是两个读取器一次读取 2 个字节。我正在使用 Ubuntu、GCC mkfifo 来创建 fifo。

【问题讨论】:

    标签: c linux ipc fifo


    【解决方案1】:

    fread 被缓冲,因此它正在读取所有四个字节,然后给你你要求的两个。

    要获得您所寻求的行为,请使用openread 而不是fopenfread

    【讨论】:

      【解决方案2】:

      您可能已经简化了此示例,删除了此功能,但为什么读者不等待确保文件存在?比如:

      while (!fopen("fifo1","rb) {
        wait(10);
      }
      fread...
      

      或者至少确保它是开放的

      if (!fopen("fifo1", "rb) {
        printf("error, cannont open file");
      }
      

      也手动测试每个脚本。经营作家。并检查文件是否符合您的期望。手动将文件放在那里并检查阅读器是否确实在查找和阅读文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-30
        • 1970-01-01
        • 2014-11-12
        • 1970-01-01
        相关资源
        最近更新 更多