【问题标题】:How to view /proc/ information of a child proccess?如何查看/proc/子进程的信息?
【发布时间】:2014-09-15 12:44:13
【问题描述】:

具体来说,我想查看 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);
}

在调用 wait 之前可以访问该文件,但它当然不包含任何非零值,因为孩子尚未完成。调用等待后该文件不可访问,因为子进程已终止。那么,我该怎么做呢?

诚然,这是针对一个项目的,但除了基本的分叉之外,我们还没有涵盖任何内容。任何帮助表示赞赏。

【问题讨论】:

  • 当进程终止并收集子进程时,/proc 中的相应条目消失。你需要什么信息?另外,请指定您的操作系统,因为 proc 文件系统既不是 POSIX 也不是 System V 的一部分。
  • 对我来说这听起来像是一个XY Problem 实例。请尝试说明您需要该访问权限的原因。
  • 对不起,我ssh到的其实是我学校提供的Linux机器。根据项目描述,我需要 /proc/PID/io 文件中的“bytes_read”和“bytes_written”的值。

标签: c linux


【解决方案1】:

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

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

编辑:

这是一些代码(需要 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);
    }

}

【讨论】:

  • 我会试试的。谢谢您的帮助。编辑:如何在信号处理程序中获取孩子的 PID?
  • @Robbeh 简单的解决方案:将其放入全局变量中。便携式解决方案:使用较新的sigaction 信号 API,它可以具有接收 PID 作为参数的函数。但理想情况下,您不应该在信号处理程序中运行任何大的东西。您可以在那里做的大多数事情都不是信号安全的!
  • 啊,当然。非常感谢。并感谢您提供示例代码。
猜你喜欢
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多