1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <dirent.h>
  5. #include <errno.h>
  6. #include <ctype.h>
  7. #include <string.h>
  8.  
  9. int main (int argc, char *argv[]) {
  10.  
  11. DIR *dir_pointer, *proc_dir;
  12. struct dirent *dir_structure, *proc_struct;
  13.  
  14. FILE *fp;
  15.  
  16. int pid, ppid;
  17. char *pname;
  18. char pstate;
  19.  
  20. int i = 0;
  21.  
  22.  
  23. /*open directory stream*/
  24. dir_pointer = opendir("/proc/");
  25. printf("openning /proc/ dir\n");
  26.  
  27. char *digit_dir; //all process id
  28. char **subdir; //subdirectory for the processes
  29. subdir = (char**) calloc(sizeof(char**), 5000);
  30. //store at least 5000 processes
  31. int j = 0;
  32. /*reading reading files and directory*/
  33. while((dir_structure = readdir(dir_pointer)))
  34. {
  35. i++;
  36. digit_dir = (char*) (dir_structure->d_name);
  37.  
  38.  
  39. //store only directory that are process ID
  40. if(isdigit(dir_structure->d_name[0])){
  41. subdir[j]= (char*) dir_structure->d_name;
  42. j++;
  43. }
  44.  
  45. }
  46.  
  47. char *root = "/proc/";
  48. char *file;
  49. char *new;
  50.  
  51. printf("pid \t pname \t \t \t pstate \t ppid\n");
  52. while(*(subdir)!=NULL){
  53.  
  54. new = (char *)calloc(strlen(root) + strlen(*subdir) + 1, sizeof(char));
  55. strcat(new, root);
  56. strcat(new, *subdir);
  57.  
  58.  
  59. file = (char *)calloc(strlen(new) + strlen("stats") + 1, sizeof(char));
  60. strcat(file, new);
  61. strcat(file, "/stat");
  62.  
  63.  
  64. fp = fopen(file,"r");
  65. if (fp == NULL) perror ("Error opening file");
  66. else {
  67.  
  68. pname = (char*) calloc(sizeof(char*),10);
  69. fscanf(fp, "%d", &pid);
  70. fscanf(fp, "%s", pname);
  71. fscanf(fp, "%c", &pstate);
  72. fscanf(fp, "%d", &ppid);
  73.  
  74.  
  75. printf("%d\t%s\t\t%c\t\t\t\t%d\n",pid,pname,pstate,ppid);
  76.  
  77.  
  78. fclose (fp);
  79. }
  80.  
  81.  
  82. *(subdir++);
  83.  
  84. }
  85.  
  86.  
  87.  
  88.  
  89. return 0;
  90. }