1.free命令详解
free是每个Linux Distribution都会自带的系统命令,用于统计系统当前的物理内存使用情况,可以使用-b/-k/-m参数来指定显示单位,默认为-k。命令执行结果及解释如下:
Mem
total:内存总数 49913092 kb
used:已使用内存数 3558828 kb
free:未使用内存数 46354264 kb
shared:共享内存 0 kb(进程间通过共享内存实现IPC,很少使用)
buffers:buffer cache内存数 278292 kb
cached:page cache内存数 3000000 kb
注:total = used + free
-/+ buffers/cache
used:系统已使用的不包括buffer及cache的内存数 280536 kb,与Mem中的used - buffers - cached相等
free:系统未使用的包括buffer及cache的内存数 49632556 kb,与Mem中的free + buffers + cached相等
注:total = used + free。第一行的Mem中,将buffers及cached统计为已使用used,而第二行-/+ buffers/cache中,将buffers及cached统计为未使用free。可以看出,第一行的free反应的是可以使用的内存总数,第二行的free反应的是可以挪用的内存总数(第一行的free + buffers + cached)
Swap
交换空间,虽然被统计为内存,实际是在硬盘分割出来的一块(逻辑上存在于内存,物理上存在于硬盘),其文件系统格式为swap,在物理空间上采用连续分配方式(为了提高速度,而ext3、reiserfs等格式的文件系统,在物理空间上则采用索引分配方式,为了提高空间利用率)。一般在内存够用的情况下,交换空间都不会被用到,used通常为0。只有当物理内存不够用时,暂时不运行的进程才会被交换到swap(但是进程打开的文件被写回文件系统,不会被交换到swap),而将当前需要运行的内存换入内存。
2.buffer与cache
关于buffer与cache的区别,可以参考这篇文章:http://blog.csdn.net/genius_lg/article/details/14454935
3.flush/fflush sync/fsync
flush
fflush
SYNOPSIS
#include <stdio.h>
int fflush(FILE *stream);
DESCRIPTION
The function fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected. If the stream argument is NULL, fflush() flushes all open output streams.
当我们调用库函数fopen()打开一个文件,再调用库函数fwrite()写文件成功后,实际并未真正的将数据写到磁盘的文件中,甚至没有写到内核缓冲区,而只是将数据写到了用户空间缓冲区(缓冲区根据使用C库的不同而不同,如glibc的缓冲区)。如果我们想要把数据真正的写到磁盘的文件中,还需要调用fflush()将用户缓冲区的数据写到内核缓冲区,再调用fsync()将内核缓冲区的数据写入磁盘。
sync
fsync
SYNOPSIS
#include <unistd.h>
int fsync(int fildes);
DESCRIPTION
The fsync() function shall request that all data for the open file descriptor named by fildes is to be transferred to the storage device associated with the file described by fildes in an implementation-defined manner. The fsync() function shall not return until the system has completed that action or until an error is detected.
当我们调用系统调用open()打开一个文件,再调用系统调用write()写文件成功后,实际并未真正的将数据写到磁盘的文件中,甚至没有写到内核缓冲区,而只是将数据写到了内核空间缓冲区。如果我们想要把数据真正的写到磁盘的文件中,还需要调用fsync()将内核缓冲区的数据写入磁盘。