c - 读取/proc/pid/mem 文件不返回任何内容

标签 c linux file proc

我想通过读取/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;
}

最佳答案

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

真的。

/proc/<pid>/mem是一个旧界面,与 dd 一起使用仍然很可爱来自 shell(“一切都是文件”等),但是从 C 中打扰它是没有意义的。

关于c - 读取/proc/pid/mem 文件不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64178018/

相关文章:

c - 获取以逗号分隔的数字

c++ - 如何使负载平衡代理更加完全异步?

c++ - Linux 中的权限被拒绝

android - 时间不能跑早午餐?

c - 如何将指向结构的指针数组初始化为零

python - 如何将文件的大小和名称放入字典中

c++ - 为什么while中的循环计数器超出了整型变量的范围,所以不是无限循环?

ruby-on-rails - 在 Rails 中保存视频文件

c# - 创建一个只能由我的程序使用的文件。我如何将它与其他程序的文件区分开来?

c - 这是关于 LINUX 中的共享内存