Execve () and file descriptor sharing

I read from the execve man pages that if a process call (A) execve, already open file descriptors are copied to the new process (B).

Two possibilities are possible here: -

1) Does this mean that a new file descriptor table is created for process B, records that are copied from the old process A file descriptor table

2) Or, process B receives the file descriptor table of process A, because after process execve A will cease to exist, and already open files can only be closed from process B if it receives the file descriptor table of process A.

Which one is correct?

+4
source share
2 answers

Which one is correct?

# 2

Although what you ask for is more related to the details of the OS implementation, and this is rarely ever important for applications, completely transparent to applications and OS dependent.

It is commonly said that a new process inherits file descriptors. Except for those with the FD_CLOEXEC flag set, obviously.

Even in case # 1, if we assume that for a short time both processes A and B are in memory (in fact, for this area fork ()), copying the table fd would be fine. Since process A will be terminated (using exec ()), all of its file descriptors will be close () d. And this will not affect the already copied file descriptors in process B. File descriptors are similar to pointers to the corresponding kernel structure containing actual information about what the file descriptor actually indicates. Copying the fd table does not create copies of the underlying structures - it only copies pointers. The kernel structure contains a reference counter (necessary to implement fork ()), which increases during copying and, thus, knows how many processes use it. Calling close () in a file descriptor first of all leads to a decrease in the reference count. And only if the counter goes to zero (the structure does not use more processes), then only the OS actually closes the main file / socket / pipe / etc. (But, obviously, even if two processes are present within the kernel for some short time at the same time, user space applications cannot see this, since the new process after exec () also inherits the PID of the original process.)

+5
source

execve does not create a new process. It replaces the call program image, memory space, etc. New based on the executable from the file system. The file descriptor table is changed by closing any descriptors with the close-on-exec check box selected; the rest remain open and in the same state in which they were (current position, locks, etc.) until execve .

You are probably confusing this with what happens on the fork , since execve usually precedes fork . When the fork process, the child process has a new file descriptor table related to the same open file descriptions as the parent process descriptor table.

+12
source

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


All Articles