通過proc 目錄遍歷進程

#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 128
int main(void)
{
    DIR *dir;
    struct dirent *entry;
    FILE *fp;
    char path[PATH_SIZE];
    char buf[MAX];
    printf("NAME\t\tPID\n"); /* 輸出表頭 */
    if((dir = opendir( "/proc" )) == NULL ) { /* 打開/proc目錄 */
        perror("fail to open dir");
        return -1;
    }
    while((entry = readdir( dir ) ) != NULL){
        if(entry->d_name[0] == '.') /* 跳過當前目錄,proc目錄沒有父目錄 */
            continue;
        /* 跳過系統信息目錄,所有進程的目錄全都是數字,而系統信息目錄全都不是數字 */
        if( (entry->d_name[0] <='0' ) || (entry->d_name[0] >= '9'))
            continue;
        /* 使用sprintf完成拼接路徑,其中兩個%s會由entry->d_name表示的進程ID替
        代 */
        sprintf(path, "/proc/%s/task/%s/status", entry->d_name,entry->d_name);
        fp = fopen(path, "r"); /* 打開文件 */
        if(fp == NULL){
            perror("fail to open");
            exit(1);
        }
        while(fgets(buf, MAX, fp) != NULL){ /* 讀取每一行 */
            if(buf[0] == 'N'
               && buf[1] == 'a'
               && buf[2] == 'm'
               && buf[3] == 'e')
            {
                int i=6;
                while(buf[i]!='\n')
                {
                    printf("%c", buf[i]); /* 跳過‘\t’,輸出狀態信息 */
                    i++;
                }
            }
            if(buf[0] == 'P'
               && buf[1] == 'i'
               && buf[2] == 'd'){
                printf("\t\t%s", &buf[5]); /* 輸出PID後就結束循環 */
                break;
            }
        }
        fclose(fp); /* 關閉stattus文件 */
    }
    closedir( dir ); /* 關閉目錄 */
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章