从/向FIFO读/写

时间:2012-08-27 03:37:04

标签: c linux ipc fifo

我一直在尝试实现fifo写入和读取,方案是这样的,writer1将4个字节写入fifo,reader1读取2个字节,reader2读取接下来的2个字节,下面是我所做的,

writer.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。

2 个答案:

答案 0 :(得分:0)

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

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

或者至少确保它是开放的

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

也可以手动测试每个脚本。跑一个作家。并检查文件是否符合您的预期。手动放置文件,检查读者是否正在查找和读取文件。

答案 1 :(得分:0)

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

要获得您寻求的行为,请使用openread代替fopenfread

相关问题