I am trying to measure the amount of memory used by a child process via the getrusage system call with the following code
#include <iostream>
using std::cout;
using std::endl;
#include <unistd.h>
#include <thread>
#include <chrono>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <cassert>
#include <vector>
int main() {
auto child_pid = fork();
if (!child_pid) {
cout << "In child process with process id " << getpid() << endl;
cout << "Child's parent process is " << getppid() << endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::vector<int> vec;
vec.resize(10000);
for (auto ele : vec) {
cout << ele << endl;
}
} else {
// this will wait for the child above to finish
waitpid(child_pid, nullptr, 0);
struct rusage usage;
int return_val_getrusage = getrusage(RUSAGE_CHILDREN, &usage);
assert(!return_val_getrusage);
cout << "Memory used by child " << usage.ru_maxrss << endl;
}
return 0;
}
I keep changing the amount of memory I am allocating by putting in different arguments to the vector::resize()
call. This however always prints a value around 2300 for memory usage by child. I am not sure this is the right way to go about measuring memory usage for a child process. Even if I add calls to getrusage
with RUSAGE_SELF
in the child process before the allocation of the vector, the value of ru_maxrss
remains the same. Could someone tell me what I can do better here?