一.在对文件操作的系统调用接口,并没有提供获取对文件引用计数的信息,所有想要获取此信息,有两种方法:
1.在内核中添加一个系统调用.将内核中文件的引用count计数返回到应用层,这种比较麻烦.不推荐
2.遍历整个系统中所有进程打开此文件的个数./proc/pid/fd/**, 以此来统计引用计数.lsof和fuser可能就是用的此方法,没有做考证.
例子如下:
june_hou@ubuntu:~$ ps
PID TTY TIME CMD
936 pts/9 00:00:00 bash
3586 pts/9 00:00:00 a.out
4533 pts/9 00:00:00 ps
june_hou@ubuntu:~$ ls -al /proc/3586/fd/ -al
total 0
dr-x------ 2 june_hou june_hou 0 Jan 11 13:26 .
dr-xr-xr-x 9 june_hou june_hou 0 Jan 11 13:26 ..
lrwx------ 1 june_hou june_hou 64 Jan 11 13:26 0 -> /dev/pts/9
lrwx------ 1 june_hou june_hou 64 Jan 11 13:26 1 -> /dev/pts/9
lrwx------ 1 june_hou june_hou 64 Jan 11 13:26 2 -> /dev/pts/9
lrwx------ 1 june_hou june_hou 64 Jan 11 13:26 3 -> /home/june_hou/test.log
lrwx------ 1 june_hou june_hou 64 Jan 11 13:26 4 -> /home/june_hou/test.log
june_hou@ubuntu:~$ lsof test.log
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
a.out 3586 june_hou 3u REG 252,7 0 357 test.log
a.out 3586 june_hou 4u REG 252,7 0 357 test.log