Taz bisounours-codeur | Code :
- /**
- * Un ps tres rudimentaire
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <sys/types.h>
- #include <dirent.h>
- /**
- * Dertermine si une d est un repertoire relatif a un processus
- */
- static int is_procdir(const struct dirent *d)
- {
- if(d==NULL || d->d_type!=DT_DIR)
- {
- return 0;
- }
- else
- {
- size_t i, len=strlen(d->d_name);
-
- for(i=0; i<len; ++i)
- {
- if(!isdigit(d->d_name[i]))
- {
- return 0;
- }
- }
- }
- return 1;
- }
- /**
- * Tri de dirent sur un critere de croissance numerique
- */
- static int reverse_numsort(const void *a, const void *b)
- {
- long unsigned ai, bi;
- if(sscanf((*(const struct dirent **)a)->d_name, "%lu", &ai) != 1
- || sscanf((*(const struct dirent **)b)->d_name, "%lu", &bi) != 1)
- {
- return 0;
- }
- return bi - ai;
- }
- /**
- * Affiche les informations relatives a un processus selon /proc/<pid>/stat
- */
- static void print_procinfo(const char *procdir)
- {
- char fullpath[sizeof "/proc/" + NAME_MAX + 1 + sizeof "/stat"];
- sprintf(fullpath, "/proc/%s/stat", procdir);
- FILE *F=NULL;
- if((F=fopen(fullpath, "r" )) == NULL)
- {
- perror("fopen" );
- return;
- }
- pid_t pid;
- char name[NAME_MAX + 1];
- if(fscanf(F, "%d (%[^)]s)", &pid, name) == 2)
- {
- printf("pid=%-6d\tname=%s\n", pid, name);
- }
- else
- {
- printf("Erreur\n" );
- }
- fclose(F);
- }
- int main()
- {
- struct dirent **namelist=NULL;
- int n;
-
- n=scandir("/proc", &namelist, is_procdir, reverse_numsort);
-
- if(n < 0)
- {
- perror("scandir" );
- }
- else
- {
- printf("--- %d processus ---\n", n);
- while(n--)
- {
- print_procinfo(namelist[n]->d_name);
- free(namelist[n]);
- }
- free(namelist);
- }
- return 0;
- }
|
|