红联Linux门户
Linux帮助

Linux下df与du命令输出区别简析

发布时间:2014-08-26 10:57:18来源:ha97.com作者:linux

PS:前些时间有童鞋问我,为什么他的服务器里用df和du命令查询的文件大小显示不一样。其实这两个命令查询原理是不一样的,简析如下:


1、正常情况下,df和du输出结果都会有差距

du -sh命令通过将指定文件系统中所有的目录、符号链接和文件使用的块数累加得到该文件系统使用的总块数;

而df命令通过查看文件系统磁盘块分配图得出总块数与剩余块数。

文件系统分配其中的一些磁盘块用来记录它自身的一些数据,如i节点,磁盘分布图,间接块,超级块等。这些数据对大多数用户级的程序来说是不可见的,通常称为Meta Data。

du命令是用户级的程序,它不考虑Meta Data,而df命令则查看文件系统的磁盘分配图并考虑Meta Data。

因此正常情况下,df计算的USED空间会比du计算的结果要稍大。


2、异常情况下,df计算的USED空间会比du大很多

这也是之前碰到的问题,df查看结果文件系统100%使用了,而du的结果是还有6GB空闲的,就这么个问题硬件厂商一个SUPPORT居然不知道怎么解释,这也是让我好奇晚上回来查查看究竟的原因,结果GOOGLE一下就有了。

原因在于du是以文件名、目录名为依据计算空间使用的,而df是以硬盘块使用情况来计算空间使用的。

当一个应用程序正在写一个大文件的时候,我们RM或者MV了这个文件(UNIX是允许这么干的,WINDOWS在这一点上傻有傻福),应用程序会占有句柄,并根据句柄所指磁盘位置直接写磁盘,而不会检查该文件是否被删除。

因此就会产生上述的问题。具体到Oracle层面,可能发生这种情况的有:Oracle因为某种原因在生成很大的TRACE文件,可能导致oracle等目录满,如果此时直接RM或MV掉该TRACE文件会发现空间并不会释放,进而可能导致Oracle数据库DOWN机。

解决办法:使用“> tracefile.trc”命令清空掉该文件,如果需要保留TRACE文件便于事后分析问题,可以使用CP先复制该文件到其他地方,然后清空掉原来的文件。


关于df和du的输出差别原文解释如下:

Problem Definition

This section gives the technical explanation of why du and df sometimes report
different totals of disk space usage.

When a program that is running in the background writes to a file while the
process is running, the file to which this process is writing is deleted.
Running df and du shows a discrepancy in the amount of disk space usage. The
df command shows a higher value.

Explanation Summary

When you open a file, you get a pointer. Subsequent writes to this file
references this file pointer. The write call does not check to see if the file
is there or not. It just writes to the specified number of characters starting
at a predetermined location. Regardless of whether the file exist or not, disk
blocks are used by the write operation.

The df command reports the number of disk blocks used, while du goes through the
file structure and reports the number of blocks used by each directory. As
far as du is concerned, the file used by the process does not exist, so it does
not report blocks used by this phantom file. But df keeps track of disk blocks
used, and it reports the blocks used by this phantom file.