【发布时间】: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。
【问题讨论】: