我的函数从 读取进程列表/proc,然后将进程psinfo文件读入适当的结构,以及有关该文件的数据,并打印出来。问题是,这些结构中的一些数据是错误的。像往常一样,程序部分工作的那一刻是最令人困惑的。它正确读取所有数据,除了 PID (pr_pid) 始终为 0,文件的 UID 也始终为 0。为什么?数据是否可以部分正确加载?这不应该是可能的。如果我们谈论的是 PPID,0 是可能的,但是 solaris 文档清楚地指出 pr_pid 是 PID。我认为会有答案的链接,但我找不到:
http://docs.oracle.com/cd/E19963-01/html/821-1473/proc-4.html http://linux.die.net/man/3/getpwnam http://linux.die。净/人/2/统计
代码:
void printProcessInformation(char pid[]){
    //find full path name to your "stat" file
    //DIR *dir;
    //struct dirent *ent;
    //Creating string with /proc/PID
    char * s = malloc(snprintf(NULL, 0, "%s%s", "/proc/", pid) + 1);
    sprintf(s, "%s%s", "/proc/", pid);
    //Creating string with /proc/PID/psinfo (full path)
    char * fullPath = malloc(snprintf(NULL, 0, "%s%s", s, "/psinfo") + 1);
    sprintf(fullPath, "%s%s", s, "/psinfo");
    free(s);
    //printf("%s\n",fullPath);
    //Reading data from file
    FILE* file = fopen(fullPath, "r");
    char* buffer;
    buffer = (char*) malloc(sizeof(psinfo_t));
    if(file == NULL)
    {
        perror("Error: Couldn't open file");
        return;
    }
    fread((void *)buffer, sizeof(psinfo_t), 1, file);
    psinfo_t* pData = (psinfo_t*) buffer;
    free(buffer);
    buffer = (char*) malloc(sizeof(stat));
    stat(file,buffer);
    struct stat* fileStat=(struct stat*) buffer;
    printf("File owner id:%d\n",fileStat->st_uid);
    free(buffer);
    fclose(file);
    struct passwd* pw=getpwuid(fileStat->st_uid);
    //Loading data from structures
    time_t sTime=pData->pr_start.tv_sec;
    int pr_pid=pData->pr_pid;
    char* fname=pData->pr_fname;
    char* uid=pw->pw_name;
    printf("%8s %5d %16s %.24s\n", uid, pr_pid, fname, ctime(&sTime));
}