随时监控进程的内存使用大小对于服务的稳定和平时问题的查找就有很重要的意义,比如nginx+php-fpm技术栈中对于每个php-fpm的进程内存的大小会影响进程的开启数等。
那么如何查看运行中的进程占用的内存大小呢? linux提供top命令,这个可以实时查看每个进程的内存使用量,其中主要有两个参数需要注意,RES和DATA参数。
top -p pid 然后 使用 f再点击DATA对应的标识就可以看见 DATA这一列了
RES是进程实际使用的,VIRT是虚拟和物理的总和,比如php-fpm的进程有内存限制 这个只能限制住RES。
CODE是编译器获取的,VIRT和DATA是 通过 malloc和free mmap等获取的,RES是操作系统分配的。
可以使用下面的实际例子来讲解下:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(){
int *data, size, count, i;
printf( "fyi: your ints are %d bytes large\n", sizeof(int) );
printf( "Enter number of ints to malloc: " );
scanf( "%d", &size );
data = malloc( sizeof(int) * size );
if( !data ){
perror( "failed to malloc" );
exit( EXIT_FAILURE );
}
printf( "Enter number of ints to initialize: " );
scanf( "%d", &count );
for( i = 0; i < count; i++ ){
data[i] = 1337;
}
printf( "I'm going to hang out here until you hit <enter>" );
while( getchar() != '\n' );
while( getchar() != '\n' );
exit( EXIT_SUCCESS );
}复制代码
这个例子说明有多少内存分配,有多少内存被初始化,在运行时 分配了1250000字节,初始化了500000字节:
$ ./a.out
fyi: your ints are 4 bytes large
Enter number of ints to malloc: 1250000
Enter number of ints to initialize: 500000
TOp 查看结果显示复制代码
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ SWAP CODE DATA COMMAND
<program start>
11129 xxxxxxx 16 0 3628 408 336 S 0 0.0 0:00.00 3220 4 124 a.out
<allocate 1250000 ints>
11129 xxxxxxx 16 0 8512 476 392 S 0 0.0 0:00.00 8036 4 5008 a.out
<initialize 500000 ints>
11129 xxxxxxx 15 0 8512 2432 396 S 0 0.0 0:00.00 6080 4 5008 a.out复制代码
在malloc了1250000后,VIRT和DATA增加了,但是RES没变。在初始化后 VIRT和DATA没变,但是RES增加了。
VIRT是进程所有的虚拟内存,包括共享的,入动态链接库等,DATA是虚拟栈和堆的大小。RES不是虚拟的,它是内存在指定时间真实使用的内存。