I'm trying to read memory usage(PSS, specifically) of a child process by reading its proc filesystem when the child process is about to be terminated.
Following this and this answers, I managed to hook SIGCHLD signal of child process and read some data from proc filesystem. I found it works well for most of the proc filesystem, but doesn't work for /proc/PID/maps and /proc/PID/smaps. It looks like both maps and smaps are already empty when SIGCHLD signal is emitted. If it is too late to read maps and smaps when SIGCHLD is emitted, what alternative approach could I have? Any hint would be appreciated. thanks.
The following is example code copied from the second answer I linked above.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
pthread_mutex_t mutex;
void sigchldhandler(int s) {
// signals to the main thread that child has exited
pthread_mutex_unlock(&mutex);
}
int main() {
// init and lock the mutex
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
// install signal handler
signal(SIGCHLD, sigchldhandler);
pid_t child_pid = fork();
if (child_pid > 0) {
// parent
// wait for the signal
pthread_mutex_lock(&mutex);
char buffer[0x1000];
sprintf(buffer, "/proc/%d/io", child_pid);
FILE * fp = fopen(buffer, "r");
if (!fp) {
perror("fopen");
abort();
}
while (fgets(buffer, sizeof(buffer), fp)) {
printf("%s", buffer);
}
// clean up child
wait(0);
return 0;
} else if (child_pid < 0) {
perror("fork");
abort();
} else {
// child
char* args[] = { "cat", "test.txt" };
execv(args[0], args);
}
}