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