linux下删除文件后空间并未释放
这种现象具体表现在使用'du'与'df'工具查看时,得到的数据计算结果不一致,到不是其计算方法有误;而主要是有进程仍在打开使用着哪些被删除的文件,需要重置相关的进程以让它来释放这些文件句柄,最终让空间得以释放。用df 检查发现某分区可用空间很少。
df -h
用du检查发现各目录占用的空间都很少,只占用磁盘空间的十多G,有约近百G的空间莫名其妙地丢了。
du -m --max-depth=1 |sort -gr
用lsof检查后才发现原因是,有文件被删除,而进程还活着,因而造成还占用空间的现象
lsof |grep delete
lsof | awk '/deleted/ {sum+=$7} END {print sum}'
lsof will list all open files. awk then searches for the deleted ones and sums up the file sizes (in bytes).
根据lsof列出的进程号,kill这些进程后,空间就释放出来了。
出现这种现象的解释
我们从df和du命令入手,看看他们有什么差别。
关于du,有这么一段介绍:Summarize disk usage of each FILE, recursively for directories.
df,是这样的说明:df displays the amount of disk space available on the filesystem containing each file name argument
可以这样来理解,du是面向文件的命令,它遍历某个目录,把所有文件的大小加起来,都是那些看得见的东西;而df是从文件系统考虑,通过文件系统中未分配的空间来确定文件系统中已分配空间的大小。已分配空间=空间总数-未分配空间。因为基于文件系统总体来计算,相对来说df命令是报告文件系统空间使用情况最可靠的命令。
有了上面这个区别,就经常会出现df已经显示没有空间可用而du显示当前目前没有多少东西的情况。们可以使用lsof命令,要看谁打开了那些被删除的文件,用'lsof | grep delete'。
ext2文件系统的作者也曾为这个现象做过解释:
‘df’ command says partition is full, while ‘du’ reports free space
Theodore Ts’o, the ext2 developer, said:
The standard cause for this is some user process keeping a deleted file open. When this happens, the space is not visible via ‘du’, since the file is no longer visible in the directory tree. However, the space is still used by the file until it is deallocated, and that can only happen once the last process which has the file open either closes its file descriptor to the file, or the process exits. You can use the lsof program to try to find which process is keeping an open file. Usually it’s some log file, or some large data base file which gets rotated out, but some older process are still keeping the log file open.