Reputation: 423
A parent process writes integers from an array sequentially into a pipe.
...
close(thePipe[0]);
int array[]={1, 2, 5, 5, 5};
int j;
for(j=0; j<sizeof(array)/sizeof(int); j++){
write(thePipe[1], &(array[j]), sizeof(int));
}
close(thePipe[1];
...
Its child process reads those integers and sums them up.
...
close(thePipe[1]);
int sum = 0;
int buffer;
while( 0 != read(thePipe[0], &buffer, sizeof(buffer)) ){
sum = sum + buffer;
}
close(thePipe[0]);
...
How does the child know when to read from the pipe?
Even if the child gets a lot more CPU time it still will not read before the parent hasn't written to the pipe. How does that work?
Upvotes: 0
Views: 340
Reputation: 403
Since there is nothing to read form pipe the child process will wait (blocked) until parent write something into the pipe.
Upvotes: 4
Reputation: 262814
The OS takes care of this. When you read from a pipe, execution will block until there is data available. Your program won't use CPU time while waiting that way.
Upvotes: 4