Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When piping, why do you have to close() the opposite end of a pipe before using dup2()?

Tags:

c

pipe

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;
}
like image 294
Ryan Avatar asked Oct 29 '25 20:10

Ryan


1 Answers

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.

like image 63
Kevin Keane Avatar answered Oct 31 '25 10:10

Kevin Keane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!