我想获取qnx上的进程内存。在shell上,我可以使用命令showmem -P pid
来获得结果。在c中,我为该命令打开了一个管道,但随后我想解析该命令的输出,但我不知道它是如何完成的。
int main()
{
pid_t self;
FILE *fp;
char *command;
self=getpid();
sprintf(command,"showmem -P %d",self);
fp = popen(command,"r");
// Then I want to read the elements that results from this command line
}
您使用popen和showmem的想法是可行的。您只需要解析popen()的结果,就可以提取内存信息。
这里有一个例子,假设您没有共享对象:
int main(int argc, char *argv[]) {
pid_t self;
FILE *fp;
char command[30];
const int MAX_BUFFER = 2048;
char buffer[MAX_BUFFER];
char* p;
char* delims = { " ," };
int memory[] = {-1, -1, -1, -1, -1 };
int valueindex = -1;
int parserindex = 0;
self = getpid();
sprintf(command, "showmem -P %d", self);
fp = popen(command, "r");
if (fp) {
while (!feof(fp)) {
if (fgets(buffer, MAX_BUFFER, fp) != NULL) {
p = strtok( buffer, delims );
while (p != NULL) {
if (parserindex >=8 && parserindex <= 13) {
memory[++valueindex] = atoi(p);
}
p = strtok(NULL, delims);
parserindex +=1;
}
}
}
pclose(fp);
}
printf("Memory Information:n");
printf("Total: %in", memory[0]);
printf("Code: %in", memory[1]);
printf("Data: %in", memory[2]);
printf("Heap: %in", memory[3]);
printf("Stack: %in", memory[4]);
printf("Other: %in", memory[5]);
return EXIT_SUCCESS;
}
该程序生成以下输出:
Memory Information:
Total: 851968
Code: 741376
Data: 24576
Heap: 73728
Stack: 12288
Other: 0