与维基百科相比,什么样的文件描述符描述更简单?为什么需要它们?比如说,以壳进程为例,它是如何应用的呢? 进程表是否包含多个文件描述符?如果是,为什么?
当前回答
文件描述符只是任何开放资源的引用。只要您打开一个资源,内核就假定您将对其进行一些操作。所有通过程序和资源的通信都发生在一个接口上,这个接口由文件描述符提供。
由于一个进程可以打开多个资源,所以一个资源可能有多个文件描述符。 你可以通过简单地运行, Ls -li /proc/<pid>/fd/这里的pid是进程的进程id
其他回答
这里提供的所有答案都很棒,这是我的版本
文件描述符是非负整数,充当“文件”或I/O资源(如管道、套接字或数据流)的抽象句柄。这些描述符帮助我们与这些I/O资源进行交互,并使使用它们变得非常容易。I/O系统对于用户进程来说是一个字节流(I/O流)。Unix进程使用描述符(小的无符号整数)来引用I/O流。与I/O操作相关的系统调用以一个描述符作为参数。
有效的文件描述符范围从0到可配置的最大描述符数(ulimit, /proc/sys/fs/file-max)。内核为FD表的std输入(0),std输出(1)和std错误(2)分配desc.。如果文件打开失败,fd返回-1。
当进程成功请求打开一个文件时,内核返回一个文件描述符,该描述符指向内核全局文件表中的一个条目。文件表项包含文件的inode、字节偏移量和该数据流的访问限制(只读、只写等)等信息。
In simple words, when you open a file, the operating system creates an entry to represent that file and store the information about that opened file. So if there are 100 files opened in your OS then there will be 100 entries in OS (somewhere in kernel). These entries are represented by integers like (...100, 101, 102....). This entry number is the file descriptor. So it is just an integer number that uniquely represents an opened file for the process. If your process opens 10 files then your Process table will have 10 entries for file descriptors.
类似地,当您打开一个网络套接字时,它也由一个整数表示,称为套接字描述符。 我希望你能理解。
文件描述符
To Kernel all open files are referred to by file descriptors. A file descriptor is a non - negative integer. When we open an existing or create a new file, the kernel returns a file descriptor to a process. When we want to read or write on a file, we identify the file with file descriptor that was retuned by open or create, as an argument to either read or write. Each UNIX process has 20 file descriptors and it disposal, numbered 0 through 19 but it was extended to 63 by many systems. The first three are already opened when the process begins 0: The standard input 1: The standard output 2: The standard error output When the parent process forks a process, the child process inherits the file descriptors of the parent
关于文件描述符的更多要点:
文件描述符(FD)是非负整数(0,1,2,…),它们与所打开的文件相关联。 0、1、2是标准FD,对应于程序启动时默认为shell打开的STDIN_FILENO、STDOUT_FILENO和STDERR_FILENO(在unistd.h中定义)。 FD是按顺序分配的,这意味着尽可能低的未分配整数值。 特定进程的FD可以在/proc/$pid/ FD(在基于Unix的系统上)中看到。
除了以上所有简化的回答。
如果使用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