Skip to content

Instantly share code, notes, and snippets.

@walf443
Created February 19, 2012 23:44
Show Gist options
  • Save walf443/1866537 to your computer and use it in GitHub Desktop.
Save walf443/1866537 to your computer and use it in GitHub Desktop.
get_memory_usage
void get_memory_usage(char *memsiz){
pid_t pid = getpid();
FILE *fh = popen("ps aux", "r");
char buffer[BUFSIZ];
char colbuf[BUFSIZ];
if ( fh == NULL ) {
perror("popen");
exit(1);
} else {
while ( fgets(buffer, BUFSIZ, fh) != NULL ) {
unsigned int i = 0, j = 0;
bool in_space = false;
bool is_target_pid_line = false;
unsigned int colnum = 0;
memset(colbuf, '\0', BUFSIZ);
while ( buffer[i] != '\0' ) {
if ( buffer[i] == ' ' or buffer[i] == '\t' ) {
in_space = true;
} else {
if ( in_space ) {
if ( colnum == 1 ) {
// match pid.
if ( pid == atoi(colbuf) ) {
is_target_pid_line = true;
}
}
if ( is_target_pid_line ) {
// It's target Rss size.
if ( colnum == 5 ) {
int k = 0;
while ( colbuf[k] != '\0' ) {
memsiz[k] = colbuf[k];
k++;
}
pclose(fh);
return;
}
}
colnum++;
j = 0;
memset(colbuf, '\0', BUFSIZ);
in_space = false;
}
colbuf[j] = buffer[i];
j++;
}
i++;
}
}
}
pclose(fh);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment