File descriptors and its purposes

The descriptor can be thought of as a pointer that references the actual file data in memory.

A file descriptor is a number that uniquely identifies an open file within a process. This means that if process-a is using file-a and in the file descriptor table it's denoted by 1, in process-b there can be file-b and in the file descriptor table its value can also be denoted by 1.

However, file descriptors are not only limited to files. Every I/O operation performed by the process will have a file descriptor assigned to it.

For example pipes, terminals like XTerm, devices like speakers and network sockets.

  • The kernel keeps track of how many descriptors are associated with a particular file, thereby ensuring that no two processes can modify it at the same time.

  • The kernel also keeps track of the permissions associated with each file descriptor, ensuring that only processes with the appropriate privileges can access certain files.

    • This prevents random processes from gaining access to sensitive data, thus making systems more secure.

File descriptors are used by system calls such as read(), write(), open(), and close() to perform operations on files or other resources.

  • For example, when you call the open() system call to open a file, the operating system will return a file descriptor that your program can use to read from or write to the file.

Standard file descriptors for every process

  1. Standard-Input: FD-0

  2. Standard-Output: FD-1

  3. Standard-Error: FD-2

Almost every process will have these three FDs by default.


Did you find this article valuable?

Support Ashwin Padiyar by becoming a sponsor. Any amount is appreciated!