【发布时间】:2019-03-13 16:42:48
【问题描述】:
我正在尝试在函数中读取文件/proc/$pid/status。我可以使用fopen 打开文件,当我使用fread() 读取文件时,我得到Segmentation fault (core dumped)。
功能:
void getContextSwitches() {
FILE* fp;
int pid = getpid();
char spid[10];
snprintf(spid, 10, "%d", pid);
char buffer[3000];
size_t bytesRead;
printf("\nPid of the process is: %s", spid);
char path[50];
path[0] = '\0';
strcat(path, "/proc/");
strcat(path, spid);
strcat(path, "/status");
printf("\nPath: %s\n", path);
fp = getFile(fp, path);
if(NULL == fp) {
printf("File status is not read\n");
exit(1);
}
printf("File pointer not null");
printf("size of buffer: %ld", sizeof(buffer));
bytesRead = fread(buffer, 1, sizeof(buffer), fp);
printf("\nIt's not coming here");
fclose(fp);
}
这是我得到的输出:
Pid of the process is: 85244
Path: /proc/85244/status
File pointer not null
Size of buffer: 3000
Segmentation fault (core dumped)
buffer 大小已正确分配,fp 也不为空。我在代码的其他区域也有类似的功能,而且它们运行良好。我检查了fread() 的签名,看起来也不错。
有人可以帮我理解这背后的问题吗?
【问题讨论】:
-
请在 getFile() 中包含源代码。
-
每当您遇到(甚至怀疑)内存问题时,请始终使用 AddressSanitizer 或至少 valgrind 运行您的程序。
标签: c linux-kernel segmentation-fault fread