其实,就是,一个文件,在打开之后,调用unlink, 这会导致文件的directory entry (文件名)被删除掉;这样的话,在文件系统中按照文件名就找不到它了,所以其它进程无法再打开这个文件了。 但是因为当前进程在打开这个文件,不会导致文件被删除。在打开文件的进程推出后,这个文件也就不存在了。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = open( "/tmp/file", O_CREAT | O_RDWR, 0666 );
unlink( "/tmp/file" );
return 0;
}
下面用gdb调试。
(gdb) r
Starting program: /home/charles/anonymous_inode
Breakpoint 1, main (argc=1, argv=0xbfffefe4) at anonymous_inode.c:8
8 int fd = open( "/tmp/file", O_CREAT | O_RDWR, 0666 );
(gdb) n
9 unlink( "/tmp/file" );
ls /tmp/file -li
6029376 -rw-rw-r-- 1 charles charles 0 May 18 01:07 /tmp/file
再执行一步(unlink):
$ ls /tmp/file -li
ls: cannot access '/tmp/file': No such file or directory
但是,此时inode还是存在的:
$ lsof | grep "anonymous"
lsof: WARNING: can't stat() tracefs file system /sys/kernel/debug/tracing
Output information may be incomplete.
anonymous 4469 charles cwd DIR 8,8 36864 8519682 /home/charles
anonymous 4469 charles rtd DIR 8,8 4096 2 /
anonymous 4469 charles txt REG 8,8 8356 8541543 /home/charles/anonymous_inode
anonymous 4469 charles mem REG 8,8 1786484 146275 /lib/i386-linux-gnu/libc-2.23.so
anonymous 4469 charles mem REG 8,8 147688 146267 /lib/i386-linux-gnu/ld-2.23.so
anonymous 4469 charles 0u CHR 136,3 0t0 6 /dev/pts/3
anonymous 4469 charles 1u CHR 136,3 0t0 6 /dev/pts/3
anonymous 4469 charles 2u CHR 136,3 0t0 6 /dev/pts/3
anonymous 4469 charles 3u REG 8,8 0 6029376 /tmp/file (deleted)
最后,我们看一下 man里面对 unlink函数的解释:
ESCRIPTION
unlink() deletes a name from the filesystem. If that name was the last link to a file and no processes have the file open, the file is deleted and the space
it was using is made available for reuse.
If the name was the last link to a file but any processes still have the file open, the file will remain in existence until the last file descriptor referring
to it is closed.
If the name referred to a symbolic link, the link is removed.
If the name referred to a socket, FIFO, or device, the name for it is removed but processes which have the object open may continue to use it.