我需要向子进程发送3个char缓冲区,我想将它们视为3个独立的数据块。我想过使用read()
和write()
系统调用,但在阅读man之后我无法看到分离数据的方法 - 如果我理解正确,如果我逐个编写3个缓冲区父进程,然后一个read()
的调用将读取所有数据。当然我可以在输入缓冲区中放置一些像'\0'
这样的分隔符并将子数据分开,但我正在寻找一些更优雅的方法来实现这一点。那么,是否存在某种能够顺序传递数据的系统调用?
答案 0 :(得分:2)
One possibility is to use what stdio.h
already gives you: fdopen()
the respective ends of the pipes and use fgets()
/fputs()
with the FILE
pointers. This assumes your data doesn't contain newlines.
Some alternatives could be to use fixed sizes with read()
/write()
or to use some other delimiter and parse the received data with strtok()
. You could also send the size first so the child knows how many bytes to read in the next read()
call. There are really lots of options.
答案 1 :(得分:1)
If you have it, you can use O_DIRECT
to get a "packet-oriented" pipe, but there are limitations of course.
In general for a text-based streamed protocol having separators is cleaner in my opinion.
答案 2 :(得分:1)
You have two choices
答案 3 :(得分:1)
您可以在每个数据块之前添加标题,如果数据块可以是可变长度,则包括长度字段。读者可以读取标题,然后读取块内容。