我想写一个脚本,它具有获取过程详细信息的功能。阅读/ proc程序
到目前为止,我有
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* getField(FILE* file, char* prop, int len){
char line[100], *p;
while(fgets(line, 100, file)) {
if(strncmp(line, prop, len) != 0)
continue;
p = line + len + 1;
while(isspace(*p)) ++p;
break;
}
return p;
}
int main(int argc, char *argv[]) {
char tgid[40], status[40], *s, *n;
FILE* statusf;
printf("Please Enter PID\n");
if (fgets(tgid, sizeof tgid, stdin)) {
//Remove new line
strtok(tgid, "\n");
snprintf(status, 40, "/proc/%s/status", tgid);
statusf = fopen(status, "r");
if(!statusf){
perror("Error");
return 0;
}
s = getField(statusf, "State:", 6);
n = getField(statusf, "Name:", 5);
printf("State: %s\n", s);
printf("Name: %s\n", n);
}else{
printf("Error on input");
}
fclose(statusf);
return 1;
}
我还在寻找指针和记忆有点模糊。当我运行这个脚本没有
n = getField(statusf, "Name:", 5);
我得到正确的输出(如S - 睡觉);
但是,当我调用该函数来获取进程名称,我似乎得到了同样的输出,例如。
国家:ntary_ctx 名称:ntary_ctx
而这甚至不是正确的名称。我认为问题必须是变量保持价值的功能。但我认为,当一个函数返回它的内存然后弹出堆栈。
只是为了语义的缘故,一个C程序是不是一个脚本 – rtur
@rtur感谢,刚改了称呼。我有很多东西需要学习 –
编译所有警告和调试信息('gcc -Wall -g'),然后使用调试器('gdb')。顺便说一句,阅读更多关于C(例如[here](http://en.cppreference。com/w/c))并考虑使用'scanf'来读取一些'int' pid。 –