我想寫一個腳本,它具有獲取過程詳細信息的功能。閱讀/ 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。 –