我对open close dup的理解

本文详细解析了open和close文件操作背后的机制,包括文件描述符、文件表、V节点表及其相互关系,以及close操作如何关闭文件表并可能关闭V节点表,同时解释了dup操作的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要想对open 和close进行更为深入的理解,首先要理解一个结构关系如下图所示:



首先文件描述符是归进程所有的,

一、如果一个进程引用了open

①那么他就建立一个文件表,和V节点表。

②并将文件描述符指向该文件表,同时将文件表中的v节点指针指向V节点表。

二、文件表中的信息有:

①文件状态标志,主要标明了文件描述符的性质而不是文件的性质!!!,即只读、只写、读写、追加写、长度截短为0等等

②当前文件偏移量。这个文件偏移量是所有文件描述符共享的,多个文件描述符指向同一个文件的话,他们的当前文件描述符应该相同。

要强调的是:文件状态标志:是跟随文件描述符的而不是跟随文件的!!!

三、V节点表中的信息有:

v节点信息:主要包含了文件的类型,和对此文件进行各种操作的函数的指针。

i节点信息:i节点主要是标明了文件系统中文件名与其数据存储之间的关系。即怎样通过文件名找到文件的数据。

当前文件长度。

要强调的是:V节点是跟随文件的。即和文件是一一对应的关系,即一个文件在open时产生一个V节点。


总结:文件表与文件描述符一一对应,V节点表与文件一一对应。文件描述符与文件 之间是通过 文件表,V节点表作为桥梁的。


有了上面的知识后。就对close 与dup可以很好的理解了。


close一个文件描述符,就是关闭了文件表。而此时V节点表是否会关闭呢?要看是否还有其他文件描述符引用了该文件。如果没有了,那么V节点表也会关闭,即文件被彻底关闭了。

而dup所谓的复制文件描述符的意思是,将两个文件描述符指向同一个文件表而已。


A call to open() creates a new open file descriptionan entry in the system-wide table of open files. This entry records the file offset and the file status flags (modifiable via thefcntl(2) F_SETFL operation). A file descriptor is a reference to one of these entries; this reference is unaffected if pathname is subsequently removed or modified to refer to a different file. The new open file description is initially not shared with any other process, but sharing may arise via fork(2).

                             

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

If fd is the last file descriptor referring to the underlying open file description (seeopen(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.



the resources associated with the open file description 应该指的就是V节点表所占用的资源。

an entry in the system-wid table of open files 指的就是文件表。


参考文献:《UNIX环境高级编程》 第二版

http://linux.die.net/man/2/open

http://linux.die.net/man/2/close

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值