简体   繁体   English

并非所有写入FIFO的消息都在读取时收到

[英]Not all messages written to FIFO received on read

I've got a strange problem when working with fifo files in C under linux. 在Linux下使用C语言处理fifo文件时遇到一个奇怪的问题。

Let's begin with the code: 让我们从代码开始:

#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int args, char *argv[])
{
mkfifo("fif",0666);
int x = fork();

if(x!=0)
{
     if(strcmp(argv[1],"read")==0)
     {
     int rea=open("fif",O_RDONLY,0666);
     wait(NULL);
     char buf[50];
     read(rea,buf,50);
     printf("\n %s \n",buf);
     close(rea);
     }
}

else
{
     if(strcmp(argv[1],"write")==0)
     {
     int wri=open("fif",O_WRONLY,0666);
     write(wri,argv[2],strlen(argv[2])+1);
     close(wri);
     }
}



return 0;
}

Now some details on what I want the code to do. 现在,我要执行代码的一些细节。

After running program like this: 在运行如下程序后:

./prog write hello
./prog write how
./prog write are_you
./prog read

I want to have in terminal: 我想在终端:

hello
how
are_you

But instead of this, I'm only getting this: 但是除了这个,我只会得到这个:

are_you

The problem is: I want to write to FIFO several messages, and then by reading the FIFO, it is intended to receive whole text which is stored in it. 问题是:我想向FIFO写入几条消息,然后通过读取FIFO来接收存储在其中的整个文本。 But unfortunately only the last message is stored/writed on the standard output (terminal in this case), like the only command was executed is: 但是不幸的是,只有最后一条消息是在标准输出(在这种情况下为终端)上存储/写入的,就像执行的唯一命令是:

./prog write are_you

I tried to remove this line: 我试图删除此行:

mkfifo("fif",0666);

Because I thought, if the FIFO file already exists, this line could create and overwrite the existing FIFO file. 因为我认为,如果FIFO文件已经存在,那么此行可以创建并覆盖现有的FIFO文件。 But this didn't change anything. 但这并没有改变任何东西。

So what I have to do to make this working as intended? 因此,我必须做些什么才能使其按预期工作?

First, notice that you are writing the terminating \\0 character into the FIFO: 首先,请注意,您正在将终止\\0字符写入FIFO:

 write(wri,argv[2],strlen(argv[2])+1);

When you read the contents of the fifo you also read the \\0 characters, and pass the data to printf . 当您读取fifo的内容时,您还会读取\\0字符,并将数据传递给printf The thing is, printf stops reading the string when it finds the first \\0 so you'll only see the first message from the fifo. 事实是, printf在找到第一个\\0时停止读取字符串,因此您只会看到来自fifo的第一条消息。

You can see this clearly if you run the read program under strace : 如果在strace下运行读取程序,则可以清楚地看到这一点:

read(3, "are_you\0hello\0how\0", 50)    = 18
...(snip)...
write(1, " are_you \n", 10)             = 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM