unix网络编程中的fd是什么

1. unix网络编程中的fd是什么

1.1 fd全称是file descriptor,是进程独有的文件描述符表的索引

维基百科这样描述:

In the traditional implementation of Unix, file descriptors index into a per-process file descriptor table maintained by the kernel, that in turn indexes into a system-wide table of files opened by all processes, called the file table. This table records the mode with which the file (or other resource) has been opened: for reading, writing, appending, and possibly other modes. It also indexes into a third table called the inode table that describes the actual underlying files.[3]
File_table_and_inode_table
图片原始连接

简单的说,就是内核为每个进程维护了一个file descriptor table,file descriptor是file descriptor table的索引,file descriptor table的表项又转而可以索引到系统级的file table,file table又可以索引到系统级的inode table,而这个inode table则真正的描述了底层的文件。系统级的file table还记录了每个文件被打开的方式:读、写、追加…。file descriptor table每个进程都有一个,所以fork的会被拷贝。
这里写图片描述

1.2. 对文件描述符执行close操作时,仅仅是关闭了该进程对某文件的访问,其他进程依然能访问

close的文档如下描述:

If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted.

可以看到,只有该fd是指向某文件的最后一个fd时,文件对应资源才会被释放。

2. 访问文件需要通过系统调用,进程不能直接访问文件

To perform input or output, the process passes the file descriptor to the kernel through a system call, and the kernel will access the file on behalf of the process. The process does not have direct access to the file or inode tables.

3. 可以通过/proc/PID/fd/查看PID对应的进程打开了哪些文件

On Linux, the set of file descriptors open in a process can be accessed under the path /proc/PID/fd/, where PID is the process identifier.

4. 类Unix系统中,文件描述符还可以指向其他io设备,比如网络连接套接字、管道等

In Unix-like systems, file descriptors can refer to any Unix file type named in a file system. As well as regular files, this includes directories, block and character devices (also called “special files”), Unix domain sockets, and named pipes. File descriptors can also refer to other objects that do not normally exist in the file system, such as anonymous pipes and network sockets.

猜你喜欢

转载自blog.csdn.net/u013319359/article/details/81091176