1

I have a question regarding file descriptors in Unix and C programming.

Let's say I use pipe(fd) to get file descriptor 3 and 4 for the pipe ends, 3 connects to the read end and 4 to the write end.

Now I use dup2(fd[write_end],1) to copy the descriptor of the write end (which was 4) to file descriptor 1 in my process. If I now do close(fd[write_end]) will it close descriptor 1 or descriptor 4?

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    `write_end` will still be descriptor `4` (in your example). – Some programmer dude Oct 19 '18 at 17:52
  • Note that after the `dup2`, closing the pipe descriptor is _required_ to prevent extraneous/hanging file descriptors. See my answer here: https://stackoverflow.com/questions/52823093/fd-leak-custom-shell/52825582#52825582 – Craig Estey Oct 19 '18 at 18:30

1 Answers1

1

After a successful call to dup2, both file descriptors are valid.

When you then call close(fd[write_end]), because fd[write_end] is set to 4 this is the same as close(4). So file descriptor 1 remains open and usable.

dbush
  • 205,898
  • 23
  • 218
  • 273