c-如何查看子进程的/proc/信息



具体来说,我想查看fork()创建的子进程的/proc/PID/io文件。我只能尝试在父进程中访问它,但它总是无法访问的。

pid_t pid = fork();
if (pid < 0) // failed
{
    return;
}
else if (pid == 0) // child process
{
    char* args[] = { "cat", "test.txt" };
    execv(args[0], args);
}
else // parent process
{
    wait(NULL);
}

该文件在调用等待之前是可以访问的,但它当然不包含任何非零值,因为孩子还没有完成。由于子项已终止,因此在调用等待后无法访问该文件。那么,我该怎么做呢?

诚然,这是一个项目,但除了基本的分叉之外,我们还没有涵盖任何内容。感谢您的帮助。

当您的孩子终止时,您会收到一个信号SIGCHLD。调用wait将等待此操作,然后清理子级。

您要做的是为SIGCHLD安装一个信号处理程序,当它到达时,子进程已经是僵尸,但它的/proc条目仍然存在。然后读取/proc/[child pid]/io,然后仅读取孩子的wait,以便清理它。

编辑:

以下是一些代码(需要root(sudo)权限:

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

最新更新