简体   繁体   English

通过读取 proc/ 打印过程信息<pid> /地位

[英]printing process info through reading proc/<pid>/status

I am trying to read processes info from proc//status and I intend to first check whether the process is running or not then if its running I'll display its name for that I store the line which starts with "Name:" in a string called prev then if the process is running I should print its name through this prev but what happens is that prev is overwritten by another value I think.Here's my code: `我正在尝试从 proc//status 读取进程信息,我打算首先检查进程是否正在运行,然后如果它正在运行,我将显示它的名称,我存储以“Name:”开头的行名为 prev 的字符串,然后如果进程正在运行,我应该通过这个 prev 打印它的名称,但发生的情况是 prev 被我认为的另一个值覆盖。这是我的代码:`

char path[40], line[100], *p;
FILE* statusf;

snprintf(path, 40, "/proc/%ld/status", tgid);

statusf = fopen(path, "r");
if(!statusf)
    return;

char * prev;

while(fgets(line, 100, statusf)) {
if (strncmp(line,"Name:", 5) == 0){
   prev = line;
   continue;
}

    if(strncmp(line, "State:", 6) == 0){
    // Ignore "State:" and whitespace
    p = line + 7;
    while(isspace(*p)) ++p;
if(p[strlen(p)-1] == '\n'){
    p[strlen(p)-1] = '\0';
}
}

if (!strcmp(p,"R (running)")){
    prev = prev + 6;
    while(isspace(*prev)) ++prev;
if(prev[strlen(prev)-1] == '\n'){
    prev[strlen(prev)-1] = '\0';
}

printf("%s",prev);
}

break;

}
fclose(statusf);

} ` }`

char path[40], line[100], *p;
char * prev;

while(fgets(line, 100, statusf)) {
if (strncmp(line,"Name:", 5) == 0){
   prev = line;
   continue;
}

prev will now point to line. prev 现在将指向线。 So when the content of line changes, the changes will appear to happen in prev aswell, since prev points to the same memory as line所以当 line 的内容发生变化时,变化也会发生在 prev 中,因为 prev 指向与 line 相同的内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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