Reputation: 2385
I have an application which writes data (control data, access information etc) to one end of the pipe at parent process. At the child process, I want to read that data as it is.
Parent process performs many write() operation at many location. For reading the data into the buffer, we need to specify the length of the data
read(int fd, buffer, len).
My problem is, parent process writes variable size data every time. So how would the child process came to know the length of data.
I have tried to read single character and add it to buff as,
char ch;
int n = 0;
while(n >= 0)
{
n = read(int fd, ch, 1);
*buff = ch; buff++;
}
But it doesn't seems to way to do it
Please tell me how read variable size data in child process?
Upvotes: 2
Views: 677
Reputation: 5198
You'll need to put formatted data in the pipe, that can be decoded on the read end. That is, you'll have to specify a format/protocol to be able to understand the data that's coming out. You could specify length, or use lines ending with a \n
or \0
character, whatever suites your data.
Upvotes: 4
Reputation: 146093
Heh, you've asked one of the oldest questions there is. Many answers have been developed over the years...
All of these techniques have one thing in common: the reader must already know the encoding type and must be prepared, using program logic, to read the data conditionally according to its structure. There are, of course, libraries already written that can read XML, YAML, and JSON.
Upvotes: 4
Reputation: 409206
Two most common and simplest methods are to either write the length first in a fixed-size, or to have a special record-terminator that tells that the record has ended.
Upvotes: 4