与维基百科相比,什么样的文件描述符描述更简单?为什么需要它们?比如说,以壳进程为例,它是如何应用的呢? 进程表是否包含多个文件描述符?如果是,为什么?


当前回答

文件描述符只是任何开放资源的引用。只要您打开一个资源,内核就假定您将对其进行一些操作。所有通过程序和资源的通信都发生在一个接口上,这个接口由文件描述符提供。

由于一个进程可以打开多个资源,所以一个资源可能有多个文件描述符。 你可以通过简单地运行, Ls -li /proc/<pid>/fd/这里的pid是进程的进程id

其他回答

除了以上所有简化的回答。

如果使用bash脚本处理文件,最好使用文件描述符。

例如: 如果你想读写文件"test.txt",使用文件描述符如下所示:

FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor

# Reading from the file line by line using file descriptor
while read LINE; do
    echo "$LINE"
done <&5

# Writing to the file using descriptor
echo "Adding the date: `date`" >&5 
exec 5<&- # Closing a file descriptor

关于文件描述符的更多要点:

文件描述符(FD)是非负整数(0,1,2,…),它们与所打开的文件相关联。 0、1、2是标准FD,对应于程序启动时默认为shell打开的STDIN_FILENO、STDOUT_FILENO和STDERR_FILENO(在unistd.h中定义)。 FD是按顺序分配的,这意味着尽可能低的未分配整数值。 特定进程的FD可以在/proc/$pid/ FD(在基于Unix的系统上)中看到。

As an addition to other answers, unix considers everything as a file system. Your keyboard is a file that is read only from the perspective of the kernel. The screen is a write only file. Similarly, folders, input-output devices etc are also considered to be files. Whenever a file is opened, say when the device drivers[for device files] requests an open(), or a process opens an user file the kernel allocates a file descriptor, an integer that specifies the access to that file such it being read only, write only etc. [for reference : https://en.wikipedia.org/wiki/Everything_is_a_file ]

来自马的嘴:APUE(理查德·史蒂文斯饰)。 对于内核,所有打开的文件都由文件描述符引用。文件描述符是非负数。

当我们打开一个现有文件或创建一个新文件时,内核会向进程返回一个文件描述符。内核维护一个包含所有正在使用的打开的文件描述符的表。文件描述符的分配通常是顺序的,它们从空闲文件描述符池中作为下一个空闲文件描述符分配给文件。关闭文件时,文件描述符将被释放,并可用于进一步分配。 请看这张图片了解更多细节:

When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write(). It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error. File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n. For more information, go through 3rd chapter of APUE Book.

A file descriptor is an opaque handle that is used in the interface between user and kernel space to identify file/socket resources. Therefore, when you use open() or socket() (system calls to interface to the kernel), you are given a file descriptor, which is an integer (it is actually an index into the processes u structure - but that is not important). Therefore, if you want to interface directly with the kernel, using system calls to read(), write(), close() etc. the handle you use is a file descriptor.

系统调用上覆盖了一个抽象层,即stdio接口。这比基本的系统调用提供了更多的功能/特性。对于这个接口,您获得的不透明句柄是一个FILE*,它由fopen()调用返回。有很多很多函数使用stdio接口fprintf(), fscanf(), fclose(),它们让你的生活更简单。在C语言中,stdin、stdout和stderr分别是FILE*,在UNIX中分别映射到文件描述符0、1和2。