3

I would like to get the process memory on qnx. On a shell,I can get the result using the command showmem -P pid. In c I open a pipe for the command but then I would like to parse the output of the command but I don't know how is it done.

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
}
Bionix1441
  • 2,135
  • 1
  • 30
  • 65
  • 1
    You might want to start with actually allocating memory for the string of the command, so you don't have *undefined behavior* using the uninitialized pointer `command`. An array would be a good idea. – Some programmer dude Apr 04 '16 at 12:08
  • 1
    As for your problem of parsing the output of the command, it might be a good idea to [read about the `popen` function](http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html). Once you have done that you should hopefully know how to read the command-output. And as for asking our help, how can we help if we don't actually know what the output looks like? – Some programmer dude Apr 04 '16 at 12:10
  • I have been able to retrieve the memory using fscanf – Bionix1441 Apr 04 '16 at 12:59

1 Answers1

3

Your idea with the popen and showmem is feasible. You just have to parse the result from the popen() in order to extract the memory information.

Here is an example, assuming you don't have shared objects:

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;
}

This program generates the following output:

Memory Information:
Total: 851968
Code: 741376
Data: 24576
Heap: 73728
Stack: 12288
Other: 0
Daniel
  • 346
  • 3
  • 6