- 论坛徽章:
- 4
|
以下只是个人分析,若有错误之处,希望能得到指正。谢谢!
我使用vim编辑器编辑也有和你一样的结果。
strace vim后发现vim是这样操作的。(以下只是示意,与实际输出有差别)
打开时:- open("test",O_RDONLY) = 3;
- read(3);
- close(3);
复制代码 写时:- unlink("test~");
- rename("test","test~");
- open("test", O_WRONLY|O_CREAT|O_TRUNC) = 3;
- write(3);
- close(3);
- unlink("test~");
复制代码 对于unlink,SUSV3的unlink页有这样一段话:- If one or more processes have the file open when the last link is removed, the link shall be removed before unlink() returns, but the removal of the file contents shall be postponed until all references to the file are closed.
复制代码 对于rename,SUSV3的rename页有这样一段话用来说明新的文件名:- If one or more processes have the file open when the last link is removed, the link shall be removed before rename() returns, but the removal of the file contents shall be postponed until all references to the file are closed.
复制代码 但是对于旧文件名没有说明,而我自己系统的man -s 2 rename页有这样一段话(系统为:3.6.11-4.fc16.i686 GNU/Linux,c语言库为glibc-2.14.90-24.fc16.9.i686):- Open file descriptors for oldpath are also unaffected.
复制代码 对于以上都没有在系统上验证,认为文档与实现是相符的。
通过以上的资料,我是这样认为的:
程序先写部分数据到文件,然后vim读取数据到缓存,删除数据,然后rename原文件,程序中打开的文件描述符无影响,但指向中间文件(文件名多了一个~),vim将删除后的数据写入原文件名新文件中,再unlink中间文件,这将导致中间文件从目录项中删除,而程序中的文件描述符指向临时文件(这与APUE中介绍的自己调用unlink产生临时文件效果一样)。所以你看到文件一直为空。实际此时如果用df命令查看磁盘空间可以发现临时文件的空间还被占用着,当文件描述符关闭后,磁盘空间才会释放。
|
|