There are two ways to implement file sharing in the same process:
- Open the same file multiple times using the Open function
- Use the DUP/DUP2 function or the FCNTL function
========================================================for the first method:each time you open a file by using the Open function, a different file table entry (struct file struct) is created in the operating system kernel, but these different struct file structures will eventually point to the same struct inode struct. Because a file can only correspond to a single struct inode struct. because each open creates a different struct file struct, it means that different file descriptors correspond to different file table entries (struct file struct). Therefore, when manipulating different file descriptors, each has its own independent current file offset, which does not affect each other. For example, the process uses open two times to open the same file, get the file descriptor Fd1 and the file descriptor Fd2 then write a portion of the data to FD1, fd1 the current file offset is updated. When the data is written to FD2, the current file offset of FD2 is still at the beginning of the file, so the data written will overwrite the data previously written to FD1. for the second method:This is explained in more detail in the notes describing the DUP/DUP2 function or the FCNTL function. There is an essential difference between this method and the first method. =======================================================in multiple processes, implement file sharing:Similar to opening the same file in different processes and using open multiple times in the same process, the operating system creates different file table entries (struct file struct), and eventually points to the same struct inode struct. Therefore, the current file offset in each process is independent and non-affected. However, unlike a single process, the sequence of operations is indeterminate, and the order of operations in a single process is deterministic because of the concurrent execution of the processes in multiple processes.
File io detailed (10)---file sharing (between multiple processes, single process)