0

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);
    }

}
joybro
  • 205
  • 1
  • 12
  • 1
    You can use `ptrace` to suspend the child when it enters the `exit_group` system call, and then you'll have access to a fully-populated /proc entry. But ptrace will also cause the child to be briefly suspended on every system call and received signal, so it's not quite transparent. – Mark Plotnick Mar 10 '21 at 16:53
  • Thank you for the answer, Mark. Would using ptrace affect some /proc data, for example, CPU times in /proc/PIC/stat? – joybro Mar 11 '21 at 12:09
  • 1
    It might add some small amount of system time - ptrace will execute some code in the kernel. – Mark Plotnick Mar 11 '21 at 14:36

0 Answers0