Linux / UNIX programming: Get all running processes specified user ID and process name

 

First obtain a system function `getpwnam` UID specify the user name, and then traverse the / proc / PID in all directories, if / proc / PID / status of the UID is the UID enter a user name corresponding to the output process name of the status file , the process ID is the name of the directory.

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <pwd.h>

int main(int argc, char const *argv[])
{
    //判断参数是否合法
    if(argc != 2) {
        perror("Arguments error: lack of username");
        exit(EXIT_FAILURE);
    }

    //获得指定用户名的ID
    errno = 0;
    struct passwd *pwd = getpwnam(argv[1]);
    if(NULL == pwd){
        if(errno == 0){
            char err_meg[50];
            sprintf(err_meg, "Not found the user: %s", argv[1]);
        } else {
            perror(strerror(errno));
        }
        exit(EXIT_FAILURE);
    }
    uid_t uid = pwd->pw_uid;
    //printf("%d\n", uid);

    //打开目录 /proc
    DIR *dir = opendir("/proc");
    if(NULL == dir){
        perror(strerror(errno));
        exit(EXIT_FAILURE);
    }

    errno = 0;
    struct dirent *pid_dir;
    while(pid_dir = readdir(dir)){
        // puts(pid_dir->d_name);

        //是pid目录
        if((pid_dir->d_name)[0] <= '9' && (pid_dir->d_name)[0] >= '1'){
            //构造 /proc/PID/status 文件名
            char status[50] = "/proc/";
            strcat (Status, pid_dir-> d_name); 
            strcat (Status, "/ Status"); 
            // open 
            int = FD Open (Status, of O_RDONLY); 
            IF (FD == -1) { 
                perror (the strerror (errno)); 
                Exit (EXIT_FAILURE); 
            } 
            // read 
            char Buffer [512]; 
            read (FD, Buffer, 512); 
            char * = uid_ptr Strstr (Buffer, "Uid") +. 5; // the UID to the character 'Uid' position 5 characters after migration 
            if ((uid_t) (strtol ( uid_ptr, NULL, 10)) == uid) {// strtol: the UID is converted to the form of characters long, then converted uit_t 
                int. 6 = I; / / process name in the status file head position offset rearwardly 6 characters  
                printf ( "% s \ t" , pid_dir-> d_name);
                while (* (buffer + i) ! = '\ n') {// output process name
                    printf("%c", *(buffer + i));
                    i++;
                }
                puts("");
            }
            //关闭
            close(fd);
        }
    }

    if(0 != errno){
        perror(strerror(errno));
        exit(EXIT_FAILURE);
    }
    closedir(dir);
    return 0;
}

  

Guess you like

Origin www.cnblogs.com/yuanyb/p/11073519.html