onsdag 19 december 2012

List running process id's on linux

This is how to list all running process id's (pids) in C. Every numbered dir in /proc correlates to a running process. Open the file status to get more detailed information about the process.


#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char **argv){
  DIR *dp;
  struct dirent *ep;
  char *num = "0123456789";

  dp = opendir("/proc");
  if(dp != NULL){
    while((ep = readdir(dp))){
      if(strspn(ep->d_name, num)){
        printf("%s\n", ep->d_name);
      }
    }
    closedir(dp);
  } else {
    perror("Couldn't open the directory");
  }
  return 0;
}

Inga kommentarer: