In C, file descriptors that the child closes are also closed in the parent?

As far as I understand, Fds are integers that are used to search for open files in the kernel file description table. Therefore, if you have a code segment like this:

int fd[2], temp1, temp2; pipe(fd); temp1 = fd[0]; temp2 = fd[1]; close(temp1); close(temp2); 

All file descriptors in the pipe are closed and therefore the pipe will no longer exist. Because FDs are just ints, saying that close(temp1) identical to the expression close(fd[0]) .

In light of all this (and please let me know if I don't understand). I am confused about what happens after the fork() call. Since the child process inherits the same FD and parent state, the child FDs must be the same ints as the parents. Therefore, by this logic, if I close(fd[0]) in a child, I believe that this will also prevent the parent from accessing the file. Since close() "releases" this integer from the file descriptor table, the parent must not reference the file.

This is true? It seems very unlikely that this is a factual case, as this can lead to the fact that FDs between parents and children will be very difficult to use (especially since you do not know which process will work in the first place). So, if this logic is wrong, are FD duplicated on fork() ? How are parent and child Fds related in the file descriptor table, especially between close() calls? It helps me a lot to draw a file descriptor table, so I would like to answer as specific as possible.

Thanks for any help with this!

+5
source share
2 answers

No. What a child does on the path to closing files affects only the child copy of the file descriptors, without affecting the parent copy of the file descriptors.

However, immediately after forking, both sets of file descriptors (in the parent and child) belong to the same set of open file descriptions (pay attention to the terminology "descriptor" and "description"). If a child does things like reading or searching that affect the file’s description, then child actions also affect the parent.

You want to study the POSIX specs open() , fork() and execve() (especially the execve() page) with considerable attention.

+3
source

Parent and child have their own file descriptor tables.

If the child closes (say) the file descriptor 5, then the parent still has the open file descriptor 5.

If then the child opened another file, and it turned out that he received the descriptor 5, then the descriptor 5 of the child file will refer to a different file than the descriptor of the parent file 5 (which would not have changed).

+3
source

Source: https://habr.com/ru/post/1243187/


All Articles