Reputation: 667
In this code example, I noticed that you have to close the opposite end of a piped read buffer before writing to it, and vice versa. Why is that and what kind of consequences or side effects would there be if you didn't close the opposite end?
int main() {
char b[20];
int p[2];
int rc = pipe( p );
int pid = fork();
if ( pid > 0 ) {
close( p[0] );
rc = dup2( p[1], 1 );
}
printf( "0987654321" );
fflush( NULL );
if ( pid == 0 ) {
close( p[1] );
rc = read( p[0], b, 6 );
b[rc] = '\0';
printf( "%d-%s\n", getpid(), b );
}
return EXIT_SUCCESS;
}
Upvotes: 4
Views: 2085
Reputation: 1658
You have to close the opposite ends so that only one of your forked processes tries to read data from the pipe. For symmetry, it's a good idea to close the input side of your pipe.
The other reason for doing this is defensive programming. Eventually, you must close the pipe, or you'll be leaking file handles. If you don't need them, close them right away so you don't forget to do it later.
Upvotes: 7