In a recent interview, I told the interviewer that I was untrained and was asked this question: Please tell me what a file descriptor is. Maybe this question is a must for programmers by training. But I do get tripped up by the first question here, what exactly is a file descriptor?

Definition:

First of all, the definition of file descriptors I saw on Baidu Encyclopedia is as follows:

The kernel accesses files using file descriptors. The file descriptor is a non-negative integer. When an existing file is opened or a new file is created, the kernel returns a file descriptor. Reading and writing files also requires a file descriptor to specify the file to be read or written to.

The kernel refers to the kernel of the Linux system. File descriptors are returned by the kernel, that is, when the system itself or other software in the system needs to operate on a file, it must locate the unique file according to the descriptors returned by the system kernel. File descriptors should be similar to database IDS or index values, which are used to locate unique data values (file descriptors locate unique files).

Use of file descriptors:

Software or system processes can use system-level functions: open(), close(), read(), write(), lseek(), etc., to obtain file descriptors, operation response files. There are also three file descriptors that are most commonly used in learning C:

  • 0(c language defined by the macro nameSTDIN_FILENO, represents standard input);
  • 1(the macro name defined in C languageSTDOUT_FILENO, represents standard output);
  • 2(c language defined by the macro nameSTDERR_NO, indicating standard error handling).

For these three file descriptors, three macros have been defined in the C <unistd.h> header.

/* Standard file descriptors. */
#define STDIN_FILENO    0       /* Standard input. */
#define STDOUT_FILENO   1       /* Standard output. */
#define STDERR_FILENO   2       /* Standard error output. */
Copy the code

The functions scanf() and printf() used by our beginner C demo are the standard input and standard output file descriptors described above.

File descriptors differ from file Pointers:

File descriptors are the index of a file descriptor table saved by each Process in the PCB. Each entry has a pointer to an open file. In C, file Pointers are used as I/O handles. The FILE pointer points to a data structure called the FILE structure in the user area of the process. The FILE structure consists of a buffer and a FILE descriptor. The file descriptor is an index of the file descriptor table, so in a sense the file pointer is the handle of the handle (on Windows, file descriptors are called file handles).