qiubit
qiubit

Reputation: 4816

Passing multiple chunks of data using pipe in C

I need to send 3 char buffers to child process and I want to treat them as 3 separate chunks of data. I thought of using read() and write() system calls but after reading man I can't see a way to separate the data - if I understand it correctly, if I write 3 buffers one by one in parent process, then one call of read() will read all the data. Of course I could put some separators like '\0' in input buffers and separate the data in child, but I'm looking for some more elegant way to do this. So, is there some kind of system call that enables to pass data sequentially?

Upvotes: 0

Views: 749

Answers (4)

Ian Abbott
Ian Abbott

Reputation: 17438

You could precede each chunk of data with a header, including a length field if chunks can be variable length. The reader can read the header and then the chunk contents.

Upvotes: 1

user2371524
user2371524

Reputation:

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.

Upvotes: 2

user3386109
user3386109

Reputation: 34839

You have two choices

  1. Put delimiters in the data (as you mentioned in the question).
  2. Provide feedback from the child. In other words, after writing a chunk of data to the pipe, the parent waits for a response from the child, e.g. on a second pipe, or using a semaphore.

Upvotes: 1

unwind
unwind

Reputation: 399979

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.

Upvotes: 1

Related Questions