我正在尝试读取文件 /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()
函数中。
其余代码没问题。
我怀疑您从 getFile()
返回了无效的 FILE*
。
关于c - 读取() : Unable to read file for/proc/$pid/status,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52711953/