Since it seems that you intend to make a single read of all the data from the pipe, I think the following will serve you better than delimiter+encoding or miniheader techniques suggested in other answers:
From the pipe (7) manpage:
If all file descriptors referring to
the write end of a pipe have been
closed, then an attempt to read(2)
from the pipe will see end-of-file
(read(2) will return 0).
The following example was taken from the pipe (2) manpage and reversed so that the child does the writing, the parent the reading (just to be sure). I also added a variable size buffer. The child will sleep for 5 seconds. The delay will ensure that the exit() of the child can have nothing to do with pipeio (the parent will print a complete line before the child exits).
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
char *
slurpfd(int fd)
{
const int bytes_at_a_time = 2;
char *read_buffer = NULL;
int buffer_size = 0;
int buffer_offset = 0;
int chars_io;
while (1) {
if (buffer_offset + bytes_at_a_time > buffer_size) {
buffer_size = bytes_at_a_time + buffer_size * 2;
read_buffer = realloc(read_buffer, buffer_size);
if (!read_buffer) {
perror("memory");
exit(EXIT_FAILURE);
}
}
chars_io = read(fd,
read_buffer + buffer_offset,
bytes_at_a_time);
if (chars_io <= 0) break;
buffer_offset += chars_io;
}
if (chars_io < 0) {
perror("read");
exit(EXIT_FAILURE);
}
return read_buffer; /* caller gets to free it */
}
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
assert(argc == 2);
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]) + 1);
close(pipefd[1]); /* Reader will see EOF */
/* sleep before exit to make sure that there
will be a delay after the parent prints it's
output */
sleep(5);
exit(EXIT_SUCCESS);
} else { /* Parent reads from pipe */
close(pipefd[1]); /* Close unused write end */
puts(slurpfd(pipefd[0]));
close(pipefd[0]);
wait(NULL); /* Wait for child */
_exit(EXIT_SUCCESS);
}
}
From your comment I see now that you may want to read the data as it becomes available, to update the UI or whatever, to reflect your system's status. To do that open the pipe in non-blocking (O_NONBLOCK) mode. Read repeatedly whatever is available until -1 is returnd and errno == EAGAIN and do your parsing. Repeat unil read returns 0, which indicates that the child has closed the pipe.
To use an in-memory buffer for File* functions you can use fmemopen() in the GNU C library.