日期:2014-05-16  浏览次数:20728 次

linux 获取内存的方法
#include <sys/resource>
int getrusage(int who, struct rusage *r_usage);  


利用getrusage可以得到进程的相关资源信息。如:用户开销时间,系统开销时间,接收的信号量等等;

下面是rusage的结构:
struct rusage {
  struct timeval ru_utime; /* user time used */
  struct timeval ru_stime; /* system time used */
  long ru_maxrss;
  #define ru_first ru_ixrss
  long ru_ixrss; /* XXX: 0 */
  long ru_idrss; /* XXX: sum of rm_asrss */
  long ru_isrss; /* XXX: 0 */
  long ru_minflt; /* any page faults not requiring I/O */
  long ru_majflt; /* any page faults requiring I/O */
  long ru_nswap; /* swaps */
  long ru_inblock; /* block input operations */
  long ru_oublock; /* block output operations */
  long ru_msgsnd; /* messages sent */
  long ru_msgrcv; /* messages received */
  long ru_nsignals; /* signals received */
  long ru_nvcsw; /* voluntary context switches */
  long ru_nivcsw; /* involuntary " */
  #define ru_last ru_nivcsw
  };

如果参数who是RUSAGE_SELF,则得到的是当前进程的资源信息。如果是RUSAGE_CHILDREN,则将返回当进程的终止掉的子进程和等待子进程的资源信息。当调用成功后,返回0,否则-1;
下面是一个例子:

int who = RUSAGE_SELF;
struct rusage usage;
int ret;

ret = getrusage(who, &usage);


这样你就可以用usage获取你想要的东西了;