Skip to content

Instantly share code, notes, and snippets.

@Aruna-Hewapathirane
Last active August 29, 2015 14:05
Show Gist options
  • Save Aruna-Hewapathirane/f41e7291e15bae6062a1 to your computer and use it in GitHub Desktop.
Save Aruna-Hewapathirane/f41e7291e15bae6062a1 to your computer and use it in GitHub Desktop.
how to read from an existing proc file ( specifically /proc/<pid>/status )
// compile: gcc -Wall -o proc proc-read.c
// citation: https://bbs.archlinux.org/viewtopic.php?id=96068
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
void die(char *x){ perror(x); exit(1); };
int main(int argc, char **argv)
{
int n = 0;
char filepath[BUFFER_SIZE], buf[BUFFER_SIZE];
FILE *f = NULL;
//get the filename to open
//eg usage: proc-read "2837/status"
if(argc < 2){
fprintf(stderr, "Usage: %s <proc file>\n", argv[0]);
return 1;
}
//get the path of the file
n = snprintf(filepath, BUFFER_SIZE-1, "/proc/%s", argv[1]);
filepath[n] = 0;
//open the file
f = fopen(filepath, "r");
if(!f)
die("fopen");
//print its contents
while(fgets(buf, BUFFER_SIZE-1, f))
printf("%s", buf);
if(ferror(f))
die("fgets");
fclose(f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment