Linux 中删除正在被进程占用的文件,磁盘空间不被释放。

在 Linux 系统中,通过 rm 命令删除一个文件,实际上是在相应的目录结构中 unlink 这个文件。如果这个文件仍然被打开着,这个文件仍然可以被这个进程所使用,并将继续占用磁盘空间。等这个程序关闭该文件后,对应文件的空间才会被释放。

=== TEST STEPS ===

1. Create a 1GB file.

    [root@rhel674 ~]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/VolGroup-lv_root
                          6.5G  3.3G  3.0G  53% /
    tmpfs                 499M     0  499M   0% /dev/shm
    /dev/sda1             477M   36M  416M   8% /boot
    /dev/sdb               30G   17G   12G  58% /pool
     
     
    [root@rhel674 ~]# dd if=/dev/zero of=/largefile bs=10M count=100
    100+0 records in
    100+0 records out
    1048576000 bytes (1.0 GB) copied, 30.2106 s, 34.7 MB/s
     
     
    [root@rhel674 ~]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/VolGroup-lv_root
                          6.5G  4.2G  2.0G  69% /
    tmpfs                 499M     0  499M   0% /dev/shm
    /dev/sda1             477M   36M  416M   8% /boot
    /dev/sdb               30G   17G   12G  58% /pool
    

2. In another terminal, open this file.

    [root@rhel674 ~]# python
    Python 2.6.6 (r266:84292, May 22 2015, 08:34:51)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-15)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> f = open('/largefile', 'r+');
    >>> print f
    
    >>>
     
     
    [root@rhel674 ~]# lsof | grep largefile
    python    22423      root    3u      REG              253,0 1048576000      23936 /largefile
    

3. Delete this file. And we can see the file is still being open.

    [root@rhel674 ~]# rm -rf /largefile
    [root@rhel674 ~]#
    [root@rhel674 ~]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/VolGroup-lv_root
                          6.5G  4.2G  2.0G  69% /          <<<==== Still ocupying 1 GB space.
    tmpfs                 499M     0  499M   0% /dev/shm
    /dev/sda1             477M   36M  416M   8% /boot
    /dev/sdb               30G   17G   12G  58% /pool
     
    [root@rhel674 ~]# lsof | grep largefile
    python    22423      root    3u      REG              253,0 1048576000      23936 /largefile (deleted)
    

4. Close this file.

    >>> f.close()
    >>>
     
    [root@rhel674 ~]# lsof | grep largefile
    [root@rhel674 ~]#
     
     
    [root@rhel674 ~]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/mapper/VolGroup-lv_root
                          6.5G  3.3G  3.0G  53% /       <<<<===== 1 GB released.
    tmpfs                 499M     0  499M   0% /dev/shm
    /dev/sda1             477M   36M  416M   8% /boot
    /dev/sdb               30G   17G   12G  58% /pool