【问题标题】:Wrong value of UID in stat() and wrong pr_pid in psinfo_tstat() 中的 UID 值错误,psinfo_t 中的 pr_pid 错误
【发布时间】:2013-04-09 12:51:53
【问题描述】:

我的函数从/proc 读取进程列表,然后将进程psinfo 文件读入适当的结构,以及有关该文件的数据,并打印出来。 问题是,这些结构中的一些数据是错误的。像往常一样,程序部分工作的那一刻是最令人困惑的。它正确读取所有数据,除了始终为 0 的 PID (pr_pid) 和始终为 0 的文件的 UID。为什么?数据是否可以部分正确加载?这不应该是可能的。如果我们谈论的是 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.net/man/2/stat

代码:

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));
}

【问题讨论】:

    标签: c++ c unix solaris pid


    【解决方案1】:

    看看这个:

    psinfo_t* pData = (psinfo_t*) buffer;
    free(buffer);
     ...
    int pr_pid=pData->pr_pid;
    

    您将 pData 设置为第一行中缓冲区的内容,然后将其释放。 pData 指向的内容现在已经丢失了,实际上它可能会在下一个 malloc 中重用。当您尝试在上面的最后一行中使用它时,您正在阅读谁知道什么。在这种情况下,你释放得太激进了。不要释放 pData,(间接通过缓冲区),直到你完成使用它。

    【讨论】:

    • 是的。那,我有另一个错误,我刚刚在 stat 中发现,应该使用 stat(fullPath,buffer);
    • @Xyzk:在验证stat() 调用有效之前,不要使用struct stat 结构。 fread() 和 malloc() 也是如此。也不清楚为什么你不只是创建自己psinfo_t info; 并将&info 作为第一个参数传递给fread()。这样就节省了 malloc() 和 free() 并省去了丑陋的演员表。
    • @JonathanLeffler “也不清楚你为什么不自己创建 psinfo_t 信息;”好吧,那是因为我没有想到 :) 稍后会修改我的代码。你的其他观点也一样。出于某种原因,我不再将它们视为文件。
    猜你喜欢
    • 2016-04-11
    • 2014-04-12
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2015-10-10
    • 2021-08-29
    • 2017-09-28
    相关资源
    最近更新 更多