一、问题现象
磁盘下有个大文件占满了空间,删除后发现文件不见了,但是磁盘空间并没有释放。
问题原因
文件还被其他进程占用,调用rm
后实际上还并没有真正删除,只有当文件解除占用后(引用计数变为0)才会释放掉这部分空间。
解决方案
使用lsof
命令查看文件还在被哪个进程占用的,关闭进程接触解除占用:
1 |
lsof | grep delete |
过滤delete
表示显示出文件已经被删除了,但是实际还被进程占有着没释放的文件。
二、场景模拟
通过以下代码模拟出进程占用文件场景,代码的作用是打开文件,然后睡眠100秒,最后结束退出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char **argv) { int fd; if (argc < 2) { printf("Usage: %s file\n", argv[0]); return 0; } fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open error"); return -1; } sleep(100); close(fd); return 0; } |
编译,并在当前目录生成一个1G左右的文件用作测试:
1 2 3 4 5 6 7 8 9 10 11 |
> gcc test.c # 编译程序 > df -h /data # 当前data分区使用了12G,剩余7.5G Filesystem Size Used Avail Use% Mounted on /dev/vdb1 20G 12G 7.5G 60% /data > dd if=/dev/zero of=testfile bs=1M count=1024 # 生成一个1G左右的文件 1024+0 records in 1024+0 records out 1073741824 bytes (1.1 GB) copied, 4.7793 s, 225 MB/s > df -h /data # 目前磁盘使用了13G,剩余6.5G Filesystem Size Used Avail Use% Mounted on /dev/vdb1 20G 13G 6.5G 66% /data |
然后执行程序,程序会卡住并睡眠100S。删除测试文件,查看磁盘空间发现没有被归还:
使用lsof
命令查看文件还在被占用,kill掉之后文件解除占用,空间被归还:
评论