【问题标题】:How to get process memory on qnx如何在 qnx 上获取进程内存
【发布时间】:2016-04-04 12:04:08
【问题描述】:

我想在 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
}

【问题讨论】:

  • 您可能希望从实际为命令字符串分配内存开始,这样您就不会使用未初始化的指针command 出现未定义的行为。数组是个好主意。
  • 至于您解析命令输出的问题,read about the popen function 可能是个好主意。完成此操作后,您应该希望知道如何阅读命令输出。至于寻求我们的帮助,如果我们实际上不知道输出是什么样的,我们如何提供帮助?
  • 我已经能够使用 fscanf 检索内存

标签: c qnx qnx-neutrino


【解决方案1】:

您对 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: %i\n", memory[0]);
    printf("Code: %i\n", memory[1]);
    printf("Data: %i\n", memory[2]);
    printf("Heap: %i\n", memory[3]);
    printf("Stack: %i\n", memory[4]);
    printf("Other: %i\n", memory[5]);
    return EXIT_SUCCESS;
}

此程序生成以下输出:

Memory Information:
Total: 851968
Code: 741376
Data: 24576
Heap: 73728
Stack: 12288
Other: 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多