For the DUP and fork functions, the former copies a file descriptor, which is the copy process, and the associated file information is copied.
First, for the DUP
As already known, for a process, there is a files_struct to manage all the relevant files, the final reaction form is actually an array of files:
The so-called file descriptor is the array subscript. The DUP function always starts scanning from the first element of the array, getting the first available file descriptor (i.e., FD without associating the actual file), which is called: the DUP always uses the smallest file descriptor. It's easy to understand the principle.
What happens after a DUP operation? Look at the following figure:
For example: DUP (Fd[y]), find the first possible file descriptor (the so-called minimum descriptor) from the beginning, can now find fd[x] and Fd[y] and point to file! This tens of millions of notes, two file descriptors point to the same file and point to the same file is not the same, pointing to the same document can be different files, but the inode is always unique, but here, the FD point to a file, then any one operation, the other must be synchronous!
Common Example : In general, when initializing, the process has the default three file descriptor default representation, standard input, standard output, standard error. But this is not a mandatory rule, you can change it yourself! For example, the following code:
Close (0);
DUP (fd[x]);/* This is a file descriptor for an ordinary file */
After that, you will find that the No. 0 file descriptor is associated with this file (0 is the smallest file descriptor, so it will definitely be selected by the DUP!). )。
2. For the fork function:
After the parent process Fork, the child process and the parent process share the file that the parent process opened, and the diagram behaves as follows:
The parent-child process has the same file fd, and the corresponding FD points to the same files.
Common Example : When a parent-child process uses a pipe communication. Create a pair_pipe in the parent process, which is to create two files that can communicate, one for writing, and one for reading. Then fork, the child process copy the above information, also has the same pair_pipe as the parent process, in fact, pointing to the same file, such as:
Now close the parent process's pair_pipe[0], close the child process's pair_pipe[1], then the parent-child process uses pair_pipe[0] and pair_pipe[1] to communicate!
The specific communication diagram is as follows:
Linux file System (iii)---The file condition after the DUP and fork functions are executed