Traversing a process through the proc directory

Source: Internet
Author: User

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.