gpt4 book ai didi

c - 从 FIFO 读取/写入

转载 作者:行者123 更新时间:2023-11-30 17:58:33 24 4
gpt4 key购买 nike

我一直在尝试实现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);
}

读者.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。

最佳答案

fread 已缓冲,因此它会读取所有四个字节,然后为您提供所需的两个字节。

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

关于c - 从 FIFO 读取/写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com