I wanted this today, myself, so sharing the tested results here. I believe a call to getmem() will do what the OP asked, on any unix box. Written in very generic C, it will work in C or C++.
// Calling function must free the returned result. char* exec(const char* command) { FILE* fp; char* line = NULL; // Following initialization is equivalent to char* result = ""; and just // initializes result to an empty string, only it works with // -Werror=write-strings and is so much less clear. char* result = (char*) calloc(1, 1); size_t len = 0; fflush(NULL); fp = popen(command, "r"); if (fp == NULL) { printf("Cannot execute command:\n%s\n", command); return NULL; } while(getline(&line, &len, fp) != -1) { // +1 below to allow room for null terminator. result = (char*) realloc(result, strlen(result) + strlen(line) + 1); // +1 below so we copy the final null terminator. strncpy(result + strlen(result), line, strlen(line) + 1); free(line); line = NULL; } fflush(fp); if (pclose(fp) != 0) { perror("Cannot close stream.\n"); } return result; } int getmem() { pid_t pid = getpid(); char cmd[64]; snprintf(cmd, 64, "/bin/ps -p %d -o size", pid); char* result = exec(cmd); if (!result) { return 0; } // Find first newline. int pos = 0; while (result[pos] != '\n') { pos++; } // Remove the final newline. result[strlen(result) - 1] = '\0'; // Convert to integer. int size = atoi(result + pos + 1); free(result); return size; }
Technically, I suppose the printf(...) line should be fprintf(stderr, ...), but I tend to have stderr redirected for certain environment-specific logging reasons, and this is how I compiled and tested the code, so I'm copying verbatim to avoid breakage.