Reputation: 217
I have a parent process with two child processes fork'd off from it. I've created two pipes(one for each child). For each pipe, I have closed the write end of the parent and the read ends of the children.
The problem I am having is getting the parent to simultaneously read from each child pipe. It appears to be only reading from the first pipe I try to read from.
//PARENT
while(1)
{
read(fd[0], buffer, sizeof(buffer));
//print out buffer
read(fd2[0], buffer2, sizeof(buffer2));
//print out buffer2
}
The only thing printing is the info from my first read call. I've concluded that read seems to be blocking the other read. I've looked online and found a possible solution in select, but could not figure out how to implement it with pipes(doesn't seem to be any examples anywhere).
Could someone explain how select works with pipes or notify me of any other possible solutions to my problem?
Upvotes: 0
Views: 1817
Reputation: 28302
Your read is blocking. This means that when you call read, it waits until it either has the number of bytes you've requested or the stream is closed (hits EOF).
You either need to make the pipe non-blocking (use fcntl(fd[0], F_SETFL, O_NONBLOCK);
) or use threads.
Edit add Jonathan Leffler's point:
If you do use non-blocking it would be most efficient to call select(). This will save you wasting a lot of CPU time (which is what would happen when you enable non-blocking since the reads would immediately return when no data is present). For instance:
int fds[2];
...
fds[0] = fd[0];
fds[1] = fd2[0];
while...
select(2, &fds, NULL, NULL, NULL);
read(...);
read(...);
Upvotes: 3