I am executing a c++ program in my child process and I want to track its memory usage in the parent. Things I have tried:
- Using SIGCHLD
- Using waitpid
You can take a look at the commented code to get an idea of what I have tried.
int get_memory_usage(pid_t pid) {
int fd, data, stack;
char buf[4096], status_child[100000];
char *vm;
sprintf(status_child, "/proc/%d/status", pid);
if ((fd = open(status_child, O_RDONLY)) < 0)
return -1;
read(fd, buf, 4095);
buf[4095] = '\0';
close(fd);
data = stack = 0;
vm = strstr(buf, "VmData:");
if (vm) {
sscanf(vm, "%*s %d", &data);
}
vm = strstr(buf, "VmStk:");
if (vm) {
sscanf(vm, "%*s %d", &stack);
}
return data + stack;
}
// void handler(int sig){
// cout<<"Sig handler caught";
// }
int main() {
// signal(SIGCHLD,handler);
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";
//What am I supposed to do here?
//child pid
// time_t t;
// int status;
// pid_t childpid = pid;
// do {
// if ((pid = waitpid(pid, &status, WNOHANG)) == -1) perror("wait() error");
// else if (pid == 0) {
// time(&t);
// printf("child is still running at %s", ctime(&t));
// cout<<"Memory used: "<<get_memory_usage(childpid)<<endl;
// }
// else {
// if (WIFEXITED(status)){
// printf("child exited with status of %d\n", WEXITSTATUS(status));
// }
// else puts("child did not exit successfully");
// }
// } while (pid == 0);
}
}
The second try using waitpid is giving me the output but I get a constant value of some 300KB. But I dont think this is the actual program usage size as I am getting the same output no matter I do any sort of memory allocation in my code.
Any help would be greatly appreciated
Things I have tried:
- Using SIGCHLD
- Using waitpid