Linux 内存 virt res shr data swap 意义

 

 virt  res shr data 这几个很容易搞混了,写一下

 首先解释下含义:

 virt : 程序占用的虚拟内存

 man: The total amount of virtual memory used by the task. It includes all code, data and shared

libraries plus pages that have been swapped out and pages that have been mapped but not used.

 res  :  resident memory usage  常驻内存,也就是程序真正占用的内存

    man : The non-swapped physical memory a task has used

 shr : 共享的内存, 共享库啥的

  man:  The amount of shared memory used by a task. It simply reflects memory that could be potentially

shared with other processes

 data:  数据占用的内存 ,除了可执行文件以外的内存。

man: The amount of virtual memory devoted to other than executable code, also known as the 'data resi‐

dent set' size or DRS.

 

 swap: 交换出去的已经申请,但没有使用的空间

 man: Memory that is not resident but is present in a task. This is memory that has been swapped out

but could include additional non-resident memory. This column is calculated by subtracting phys‐
ical memory from virtual memory

.

 下面通过一些例子来说明:

#include<stdio.h>
#include<stdlib.h>


int main ()
{
 
  char  arr[ 1024*1024*1]; 
  void* p = malloc( 1024*1024*512 );
  if( NULL == p )  { printf("malloc mem fail .." ); return; }
  
  sleep(200);

}

 gcc  malloc.c -o malloc 

   运行结果:

  从上面可以看出 DATA : 堆和栈 的总和。

  从 man 的手册里面可以知道 VIRT = 4+513M + 228 ? 

 

 继续试验:

int main ()
{
 
  char  arr[ 1024*1024*1]; 
  void* p = malloc( 1024*1024*512 );
  if( NULL == p )  { printf("malloc mem fail .." ); return; }
  memset(p, 0, 1024*1024*512) ;  
  memset(arr, 0, 1024*1024*1) ;  
  sleep(200);

}

 运行结果: 

  从结果中可以看出

  RES 进程正在使用的内存空间,申请内存后并使用

 

下面继续:

   

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main ()
{
 
  char  arr[ 1024*1024*1]; 
  void* p = malloc( 1024*1024*512 );
  if( NULL == p )  { printf("malloc mem fail .." ); return; }
  int  fd = shmget( IPC_PRIVATE , 1024*1024*20 , 0666|IPC_CREAT);
  if( -1 == fd ) { return; }
  void*  pShm = shmat(fd, NULL, 0);  
  
  memset(p, 0, 1024*1024*512) ;  
  memset(arr, 0, 1024*1024*1) ;  
  memset(pShm, 2, 1024*1024*20 / 2);
  sleep(200);

}

运行结果:

 

 从上面可以看出

  SHR:  共享内存使用的空间。

  SWAP: 已经申请,但是没有使用的内存 堆 栈 共享内存

总结一下:

 VIRT :虚拟内存,包含代码段、堆栈。

 RES: 进程真正使用的内存

 SWAP: 已经申请,但是没有使用的内存

 DATA :堆+栈

 SHR : 共享内存使用的空间。

原文地址:https://www.cnblogs.com/songbingyu/p/3782405.html