如何在子进程终止之前读取子进程的/proc/PID/maps

问题描述

当子进程即将终止时,我试图通过读取其 proc 文件系统来读取子进程的内存使用情况(特别是 PSS)。

按照 thisthis 答案,我设法挂钩子进程的 SIGCHLD 信号并从 proc 文件系统读取一些数据。我发现它适用于大多数 proc 文件系统,但不适用于 /proc/PID/maps 和 /proc/PID/smaps。当发出 SIGCHLD 信号时,maps 和 smaps 看起来都已经是空的。如果在发出 SIGCHLD 时读取地图和 smap 为时已晚,我有什么替代方法?任何提示将不胜感激。谢谢。

以下是从我上面链接的第二个答案中复制的示例代码

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

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)