Created
August 11, 2016 20:37
-
-
Save kien-truong/e02c45846097f0321b96267501f12cb3 to your computer and use it in GitHub Desktop.
smemcap.c modify to return /proc/[pid]/* as string
This file contains 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
/* | |
smem - a tool for meaningful memory reporting | |
Copyright 2008-2009 Matt Mackall <[email protected]> | |
Copyright 2016 Kien Truong <[email protected]> | |
This software may be used and distributed according to the terms of | |
the GNU General Public License version 2 or later, incorporated | |
herein by reference. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <memory.h> | |
#include <errno.h> | |
#include <fcntl.h> | |
#include <dirent.h> | |
struct fileblock; | |
struct fileblock { | |
char data[512]; | |
struct fileblock *next; | |
}; | |
int readProcFile(const char *path, char** ret) | |
{ | |
struct fileblock *start, *cur; | |
struct fileblock **prev = &start; | |
int fd, r, size = 0; | |
/* buffer and stat the file */ | |
fd = open(path, O_RDONLY); | |
if (fd == -1) { | |
return -1; | |
} | |
do { | |
cur = calloc(1, sizeof(struct fileblock)); | |
*prev = cur; | |
prev = &cur->next; | |
r = read(fd, cur->data, 512); | |
if (r > 0) | |
size += r; | |
} while (r == 512); | |
close(fd); | |
char* content = (char*) malloc(size + 1); | |
int old_size = size; | |
if (content) { | |
int counter = 0; | |
/* dump file contents */ | |
for (cur = start; size > 0; size -= 512) { | |
if (size > 512) { | |
memcpy(content + counter * 512, cur->data, 512); | |
} else { | |
memcpy(content + counter * 512, cur->data, size); | |
} | |
start = cur; | |
cur = cur->next; | |
free(start); | |
counter++; | |
} | |
content[old_size] = '\0'; | |
*ret = content; | |
return 0; | |
} else { | |
return -1; | |
} | |
} | |
int readProcDir(const char *sub, const char *name) | |
{ | |
char path[256]; | |
sprintf(path, "%s/%s", sub, name); | |
char** content = malloc(sizeof(char*)); | |
int ret = readProcFile(path, content); | |
if (ret == 0) { | |
printf("File: %s\n", path); | |
printf("Content: %s\n", *content); | |
free(*content); | |
} | |
free(content); | |
return 0; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
DIR *d; | |
struct dirent *de; | |
chdir("/proc"); | |
d = opendir("."); | |
while ((de = readdir(d))) | |
if (de->d_name[0] >= '0' && de->d_name[0] <= '9') { | |
readProcDir(de->d_name, "smaps"); | |
readProcDir(de->d_name, "cmdline"); | |
readProcDir(de->d_name, "stat"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment