FIFO的实现 [英] FIFOs implementation

查看:169
本文介绍了FIFO的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

writer.c

mkfifo("/tmp/myfifo", 0660);

int fd = open("/tmp/myfifo", O_WRONLY);

char *foo, *bar;

...

write(fd, foo, strlen(foo)*sizeof(char));
write(fd, bar, strlen(bar)*sizeof(char));

reader.c

reader.c

int fd = open("/tmp/myfifo", O_RDONLY);

char buf[100];
read(fd, buf, ??);

我的问题是:

因为它不是前手知道多少字节将如何foo和酒吧都有,我怎么能知道多少字节从reader.c看?结果
因为如果我举个例子,在读阅读器和foo和bar 10个字节在一起不到10个字节,我将让他们无论是在同一个变量,而我不想要的。结果
理想的情况下我会为每一个变量一个读功能,但同样我不前手知道有多少字节将数据都有。结果
我想过增加另一写入指令writer.c写之间,用于foo和酒吧的分隔符,然后我也没问题,从reader.c对其进行解码。这是去了解它的方式?

Since it's not know before hand how many bytes will foo and bar have, how can I know how many bytes to read from reader.c?
Because if I, for example, read 10 bytes in reader and foo and bar are together less than 10 bytes, I will have them both in the same variable and that I do not want.
Ideally I would have one read function for every variable, but again I don't know before hand how many bytes will the data have.
I thought about adding another write instruction in writer.c between the write for foo and bar with a separator and then I would have no problem decoding it from reader.c. Is this the way to go about it?

感谢。

推荐答案

一个分隔符是去它的一种方式,这将正常工作,只要你知道你的数据的顺序,并使用分离器只是一个分隔符,从来没有像你的数据的一部分。

A separator is one way to go about it, and this will work fine, as long as you know the order of your data, and you use the separator as only a separator, and never as part of your data.

另一种方法是precede每个写入到管道用的字节数跟随,在一个固定的宽度。这样,你就会知道有多少数据即将回落的管道。使用一个固定的宽度,所以你知道宽度字段究竟有多长,所以你知道既当启动和停止读取数据的每个存储块。

Another way is to precede each write to the pipe with the number of bytes to follow, in a fixed width. Thus, you will know how much data is about to come down the pipe. Use a fixed width, so you know exactly how long the width field will be, so you know both when to start and stop reading each chunk of data.

这篇关于FIFO的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆