Created
October 25, 2012 18:20
-
-
Save volodymyrsmirnov/3954457 to your computer and use it in GitHub Desktop.
Get PID resident memory size for MacOS, FreeBSD and Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifdef __APPLE__ | |
#include <libproc.h> | |
#endif | |
#include <sys/resource.h> | |
#include <sys/param.h> | |
#include <sys/user.h> | |
#include <sys/sysctl.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
long getpidmemory(pid_t pid) { | |
#ifdef __APPLE__ | |
struct proc_taskallinfo pti; | |
if (proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &pti, sizeof(pti)) >= sizeof(pti)) { | |
return (long)pti.ptinfo.pti_resident_size; | |
} | |
else return -1; | |
#endif | |
#ifdef __FreeBSD__ | |
int mib[4]; | |
struct kinfo_proc proc; | |
size_t procsize; | |
mib[0] = CTL_KERN; | |
mib[1] = KERN_PROC; | |
mib[2] = KERN_PROC_PID; | |
mib[3] = pid; | |
procsize = sizeof(struct kinfo_proc); | |
if (sysctl((int*)mib, 4, &proc, &procsize, NULL, 0) >= 0) { | |
return (long)proc.ki_rssize; | |
} | |
else return -1; | |
#endif | |
#ifdef __GNUC__ | |
char *statm_path; | |
long resident_size, nul; | |
FILE *statm; | |
sprintf (statm_path, "/proc/%d/statm", pid); | |
statm = fopen (statm_path, "r"); | |
if (!statm) return -1; | |
if (7 != fscanf(statm, "%ld %ld %ld %ld %ld %ld %ld", &nul, &resident_size, &nul, &nul, &nul, &nul, &nul)) return -1; | |
else return resident_size; | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment