简体   繁体   中英

Getting pid and other process information from /proc/<pid>/status

I need to get some information (pid is just an example, i know its much easier to get it in many other ways) from /proc/PID/status

I have tried to do it this way:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <sys/procfs.h>
#include <sys/signal.h>
#include <sys/syscall.h>
#include <sys/param.h>

int main(){
        char buf[BUFSIZ], buffer[10];
        char pathbase[20], pathdir[20];
        FILE *fp;
        prstatus_t status;

        printf("Process ID: %d\n", getpid());
        printf("Parent process ID: %d\n", getppid());
        printf("Group ID: %d\n", getpgrp());
        printf("Session ID: %d\n", getsid(0));

        strcpy(pathbase,"/proc/");
        sprintf(buffer, "%d", getpid());
        strcat(pathbase, buffer);

        strcpy(pathdir, pathbase);
        strcat(pathdir,"/status");

        if((fp = fopen(pathdir, "r")) == NULL) perror("fopen");
        fread(&status, sizeof(prstatus_t), 1, fp);

        printf("Proces id: %d\n", status.pr_pid);
        printf("Proces ppid: %d\n", (int)status.pr_ppid);
        fclose(fp);
}

and it obviously wrong, cause the result i get is:

Process ID: 5474
Parent process ID: 3781
Group ID: 5474
Session ID: 3781
Proces id: 1735289198
Proces ppid: 1733560873

The thing is /proc/[pid]/status is a text file. So your fread is copying text into the struct status - so everything will look like gibberish.

You could read the status file line by line or you could use the /proc/[pid]/stat file which contains the same information on a single line ( status is for human consumption while stat is for program consumtion). To get the process id (or any other information) you would just have to tokenize that single line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM