getrusage() not giving the correct rss value for the Child process

83 views Asked by At

I have written the following code in C++ to run a C++ code in a sandboxed env and then getting its memory usage

int main() {
    int pid = fork();
    if(pid == -1){
        perror("fork"); 
        exit(EXIT_FAILURE); 
    }
    else if(pid == 0){
        cout<<"I am the child process"<<endl;
        const char* command = "/bin/sh";
        const char* arg1 = "sh";
        const char* arg2 = "-c";
        const char* arg3 = "/user_code/myprogram < /user_code/input.txt > /user_code/output1.txt";
        
        execlp(command, arg1, arg2, arg3, (char*)NULL);

        perror("execl");
        exit(EXIT_FAILURE);
    }
    else{
        cout<<"I am the parent process"<<endl;

        int status;
        struct rusage ru;

        wait(&status);

        if (WIFEXITED(status)) {
            getrusage(RUSAGE_CHILDREN, &ru);
            cout << "Memory usage (in KB): " << ru.ru_maxrss << endl;
        } else {
            cout << "Child process did not exit as expected." << endl;
        }
    }
}

The above code prints:

I am the parent process
I am the child process
Memory usage (in KB): 3584

That is very less RSS. When I run the same logic in python I get the rss as 9440 KB which is accurate when compared to my submission on codeforces

I tired running the logic on python. There it is giving the correct response.

My python code that is giving the correct response:

import subprocess
import resource



p = subprocess.Popen("/user_code/myprogram < /user_code/input.txt > /user_code/output2.txt", shell=True)
p.wait()
print(resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss)

This prints 9440 KB.

0

There are 0 answers