Skip to content

Instantly share code, notes, and snippets.

@ikcaro
Last active December 16, 2015 15:09
Show Gist options
  • Save ikcaro/5453586 to your computer and use it in GitHub Desktop.
Save ikcaro/5453586 to your computer and use it in GitHub Desktop.
Monitor de consumo de memoria para una lista de PIDs
/*
* monitor
* Angel Rodolfo Pérez Canseco(ikcaro)
* Monitor de consumo de memoria, calculo de memoria basado en pmap
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int pid;
char name[250];
unsigned long ssh;
unsigned long sro;
unsigned long swr;
unsigned long stm;
unsigned long csh;
unsigned long cro;
unsigned long cwr;
unsigned long ctm;
} PID;
int first = 1;
PID list[100];
int status_info(PID *p)
{
char buff[300];
FILE *fd = NULL;
sprintf(buff, "/proc/%d/status", p->pid);
fd = fopen(buff, "r");
if (fd == NULL)
return 0;
fscanf(fd, "Name: %s\n", p->name);
fclose(fd);
}
int maps_info(PID *p)
{
FILE *fd = NULL;
char buff[300];
unsigned start, end, diff;
char flags[50];
sprintf(buff, "/proc/%d/maps", p->pid);
fd = fopen(buff, "r");
if (fd == NULL) {
printf("%05d => No existe el proceso\n", p->pid);
return 0;
}
p->csh = 0;
p->cwr = 0;
p->cro = 0;
p->ctm = 0;
while (fgets(buff, 300, fd) != NULL) {
sscanf(buff, "%x-%x %s", &start, &end, flags);
diff = end - start;
if (flags[3] == 's')
p->csh += diff;
if (flags[3] == 'p') {
flags[3] = '-';
if (flags[1] == 'w')
p->cwr += diff;
else
p->cro += diff;
}
}
p->ctm = p->csh + p->cwr + p->cro;
if (first) {
p->ssh = p->csh;
p->swr = p->cwr;
p->sro = p->cro;
p->stm = p->ctm;
}
printf(
"%05d %-15s %-10d %-10d %-10d %-10d %-10d %-10d %-10d %-10d\n",
p->pid,
p->name,
p->csh >> 10,
(p->csh - p->ssh) >> 10,
p->cro >> 10,
(p->cro - p->sro) >> 10,
p->cwr >> 10,
(p->cwr - p->swr) >> 10,
p->ctm >> 10,
(p->ctm - p->stm) >> 10
);
fclose(fd);
}
int main(int argc, char *argv[])
{
int i;
memset(&list, 0, sizeof(list));
for (i = 1; i < argc; i++)
list[i - 1].pid = atoi(argv[i]);
while (1) {
system("clear");
printf("%-5s %-15s %-10s %-10s %-10s %-10s %-10s %-10s %-10s %-10s\n",
"PID",
"COMM",
"SHARED",
"DSHARED",
"READ",
"DREAD",
"WRITE",
"DWRITE",
"TOTAL",
"DTOTAL"
);
for (i = 0; i < argc - 1; i++) {
status_info(&list[i]);
maps_info(&list[i]);
}
first = 0;
sleep(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment