0

Let's say we have a pipe, my_pipe, which occupies file descriptors at entries 3 and 4 of the process's FDT (initial FDT scheme)

  1. First, we close the stdout standard output stream using close(1) (updated FDT scheme).
  2. Next, using dup(my_pipe[1]), we create a copy of the pipe's writing end file descriptor at the lowest available FDT entry - in our case entry 1, which was made available in the previous step.
    my_pipe[1] is now referred to by both entry 1 and entry 4 (updated FDT scheme).
  3. The following command we run is close(my_pipe[1]).

My question is - which of the file descriptors referring to my_pipe[1] will close?

Hanik
  • 1
  • 1
  • You have read documentation for `close`, haven't you? From [man close](https://man7.org/linux/man-pages/man2/close.2.html): "`close()` closes a file descriptor, so that it no longer refers to any file and may be reused.". That is, `close` closes primarily only a file descriptor, so others file descriptors referred to the same file remain usable. – Tsyvarev Nov 18 '20 at 08:50
  • @Tsyvarev, of course I've read it. If the line was `close(4)` or `close(1)` it would've been clear to me which entry will close. I'm confused because in this case `my_pipe[1]` was passed as the parameter instead of an FDT index. As I've shown, `my_pipe[1]` is referred to by two file descriptors - the original at entry 4, and the copy at entry 1, so it seems very ambiguous to me which of the two is supposed to close. I hope I made myself clear. – Hanik Nov 18 '20 at 09:16
  • Well, it seems you want to understand interoperability between `dup` and `close`. In short, `dup` creates a **new** file descriptor, which is **separated** from the **old** one from the view of `close`. So, even in your case `1` becomes a duplicate of `4`, `close(4)` doesn't close ``1``. (Since value of `my_pipe[1]` is 4, then `close(my_pipe[1])` is processed as `close(4)`). – Tsyvarev Nov 18 '20 at 09:43
  • That last sentence in the brackets made everything clear! Thanks so much for your help! – Hanik Nov 18 '20 at 09:55
  • After a successful `dup` the original fd and returned fd both refer to the same, underlying _open file description_. The _open file description_ will not be released until both file descriptors are closed. It's actually more complicated than that because `fork` effectively duplicates the parent's file descriptors into the child. Also, closing a file descriptor does not invalidate any non-anonymous `mmap` operations performed on the file descriptor, so those also get references to the _open file description_. – Ian Abbott Nov 18 '20 at 14:32
  • See: https://stackoverflow.com/q/5284062/1216776 – stark Nov 18 '20 at 14:48

0 Answers0