开发者

Unix behavior with two different processes holding descriptor to the same file and one process deleting the file

I'm a Unix newbie. I have two processes holding handles(file descriptors) to the same file on the disk.

Let the processes be A, B and the file sample.txt say

Process A is a producer (writes data to the disk file) and process B is a consumer (reads from the disk file).

Process A has reached a point where it closed the file handle (descriptor) to the disk file sample.txt, deleted the file from disk and opened a new file with the same name "sample.txt" and started writing to the new file. Meanwhile process B still has the old descriptor which points to the old file which was deleted by the process A.

Now, what happens when process B tries to read the file using it's old descriptor and will it still be able to read the old "sample.txt" file completely till the end?

Unix gurus, please throw some light on this. Any pointers to Unix kernel documents are gr开发者_StackOverflow中文版eatly appreciated.


Kernel maintains a reference count for each opened file. Second process (B) will be reading from the original file, which will not be removed from the disk until that second process closes the file descriptor, though no other processes will be able to open that old version of the file.

Edit 0:

In a little bit more detail - each file in a file system is represented by an inode, then multiple directories can point to it (these are hard links). So there are two reference counts here - on-disk link count, and in-kernel count of open(2) calls on given file (no matter through which link). A file is only removed, i.e. its inode recycled, when both counts go to zero.

To translate that to your example - When process A removes the original file, the directory entry is removed, the inode link count goes to zero, but not the open()-count. The inode is still not-free until process B calls close(2).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜