11 Tweets 9 reads Dec 24, 2022
How do we interact with Linux Filesystem via 𝐟𝐒π₯𝐞 𝐝𝐞𝐬𝐜𝐫𝐒𝐩𝐭𝐨𝐫𝐬?
A file descriptor represents an open file. It is a unique number assigned by the operating system to each file. It is an πšπ›π¬π­π«πšπœπ­π’π¨π§ for working with files. We need to use file descriptors to read from or write to files in our program.
Each process maintains its own file descriptor table.
The diagram below shows the layered architecture in Linux filesystem. Let’s take process 1234 as an example.
πŸ”Ή In User Space
When we open a file called β€œfileA.txt” in Process 1234, we get file descriptor fd1, which is equal to 3. We can then pass the file descriptor to other functions, to write data to the file.
πŸ”Ή In Kernel Space
In Linux kernel, there is a 𝐩𝐫𝐨𝐜𝐞𝐬𝐬 π­πšπ›π₯𝐞 to maintain the data for the processes. Each process has an entry in the table. Each process maintains a file descriptor table, with file descriptors as its indices.
Notice that file descriptors 0, 1 and 2 are reserved in each file descriptor table to represent stdin, stdout and stderr.
The file pointer points to an entry in the 𝐨𝐩𝐞𝐧 𝐟𝐒π₯𝐞 π­πšπ›π₯𝐞, which has information about open files across all processes. Multiple file descriptors can point to the same file table entry. For example, file descriptor 0,1 and 2 point to the same open file table entry.
Since different open file table entries can represent the same file, it is a waste of resources to store the file static information so many times. We need another abstraction layer called β€˜vnode table’ to store the static data.
In each file table entry, there is a vnode pointer, which points to an entry in 𝐯𝐧𝐨𝐝𝐞 π­πšπ›π₯𝐞. The static information includes file type, function pointers, reference counts, inode etc. inode describes a physical object in the filesystem.
πŸ”Ή In Filesystem
The inode array element stores the actual file information, including permission mode, owners, timestamps, etc. inode also points to the data blocks stored in the filesystem.
Over to you: When we close a file in a program, do you know which entries are deleted in these data structures?
Thanks for reading! Follow me at @alexxubyte to get more threads like this.

Loading suggestions...