#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char *argv[]) {
DIR *dir_pointer, *proc_dir;
struct dirent *dir_structure, *proc_struct;
FILE *fp;
int pid, ppid;
char *pname;
char pstate;
int i = 0;
/*open directory stream*/
dir_pointer = opendir("/proc/");
printf("openning /proc/ dir\n");
char *digit_dir; //all process id
char **subdir; //subdirectory for the processes
subdir = (char**) calloc(sizeof(char**), 5000);
//store at least 5000 processes
int j = 0;
/*reading reading files and directory*/
while((dir_structure = readdir(dir_pointer)))
{
i++;
digit_dir = (char*) (dir_structure->d_name);
//store only directory that are process ID
if(isdigit(dir_structure->d_name[0])){
subdir[j]= (char*) dir_structure->d_name;
j++;
}
}
char *root = "/proc/";
char *file;
char *new;
printf("pid \t pname \t \t \t pstate \t ppid\n");
while(*(subdir)!=NULL){
new = (char *)calloc(strlen(root) + strlen(*subdir) + 1, sizeof(char));
strcat(new, root);
strcat(new, *subdir);
file = (char *)calloc(strlen(new) + strlen("stats") + 1, sizeof(char));
strcat(file, new);
strcat(file, "/stat");
fp = fopen(file,"r");
if (fp == NULL) perror ("Error opening file");
else {
pname = (char*) calloc(sizeof(char*),10);
fscanf(fp, "%d", &pid);
fscanf(fp, "%s", pname);
fscanf(fp, "%c", &pstate);
fscanf(fp, "%d", &ppid);
printf("%d\t%s\t\t%c\t\t\t\t%d\n",pid,pname,pstate,ppid
);
fclose (fp);
}
*(subdir++);
}
return 0;
}