#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <fcntl.h> #define MAX 1024#define path_size 128int Main (void) { DIR *dir; struct Dirent *entry; FILE *FP; Char Path[path_size]; Char Buf[max]; printf ("name\t\tpid\n"); /* Output Header */if (dir = Opendir ("/proc") = = NULL) {/* Open/proc Directory */perror ("fail to open dir"), Return-1;} while ((entry = Readdir (dir)) = NULL) {if (entry->d_name[0] = = '. ')//* Skip the current directory, Proc directory does not have a parent directory */continue;/* Skips the System Information directory, all process directories are numbers, and The System Information directory is all not digital */if ((entry->d_name[0] <= ' 0 ') | | (Entry->d_name[0] >= ' 9 ')) Continue /* Use sprintf to complete the stitching path, where two%s will be replaced by the process ID represented by Entry->d_name */sprintf (path, "/proc/%s/task/%s/status", Entry->d_name, Entry->d_name); fp = fopen (path, "R"); /* Open File */if (FP = = null) {perror ("fail to open"); exit (1);} while (Fgets (buf, MAX, fp)! = NULL) {/* reads each line */if (buf[0] = = ' N ' && buf[1] = = ' A ' && buf[2] = = ' m ' && buf[3] = = ' E ') {int i=6; while (buf[i]!= ' \ n ') {printf ("%c", Buf[i]);/* skip ' \ t ', Output status information */i++;}} I F (buf[0] = = ' P ' && buf[1] = = ' I ' && buf[2] = = ' d ') {printf ("\t\t%s", &buf[5]);/* end loop after output PID */break ; }} fclose (FP); /* Close Stattus file */} closedir (dir); /* Close Directory */return 0;}
Traversing a process through the proc directory