File descriptors are an index into a file descriptor table stored by the kernel. The kernel creates a file descriptor in response to an open call and associates the file descriptor with some abstraction of an underlying file-like object, be that an actual hardware device, or a file system or something else entirely. Consequently a processβs read or write calls that reference that file descriptor are routed to the correct place by the kernel to ultimately do something useful.
Ref: The UNIX Time- Sharing System by DM Ritchie Β· 1974
File Descriptor
- is an integer that refers to an open file description
- the mapping of decriptor to description is local to a specific process
- the open file description is a kernel data structure, not directly accessible by the process
- other file descriptors are assigned as open() is called
- dup() and dup2() can be used to manipulate file descriptors
Ref: https://www.cs.fsu.edu/~baker/opsys/notes/unixfiles.html
File Descriptors
- 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.
πΉ 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.
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.