首页 > 解决方案 > 读取 /proc/pid/mem 文件不返回任何内容

问题描述

/proc/pid/mem我想通过读取内容并将其写入另一个文件来捕获当前进程到文件的内存映射。但是每次生成的文件都是空的。我使用sudo,所以我没有权限错误。当我将输入文件更改为某个测试文件时,例如"test_file_1.txt",一切都按预期工作。我做错了什么?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char *argv[], char *envp[]) {
    char filename[100];

    pid_t pid = getpid();
    printf("pid: %i\n", pid);

////It works with an usual file
//  FILE *in_file = fopen("test_file_1.txt", "r");

////But doesn't work with this:
    sprintf(filename, "/proc/%i/mem", pid);
    FILE *in_file = fopen(filename, "r");
    if(!in_file){
        puts("in_file can't be opened");
    }

    sprintf(filename, "mem_%i.txt", pid);
    FILE *out_file = fopen(filename, "w");
    if(!out_file){
        puts("out_file can't be opened");
    }

    char line[500];
    while(fgets(line, 500, in_file)) {
        fputs(line, out_file);             
    }

    fclose(in_file);
    fclose(out_file);

    return 0;
}

标签: clinuxfileproc

解决方案


而不是proc/<pid>/mem,您应该使用process_vm_readv(2).

真的。

/proc/<pid>/mem是一个遗留接口,在 shell 中使用它仍然很可爱dd(“一切都是文件”等),但在 C 中使用它是没有意义的。


推荐阅读