fread(): 无法读取 /proc/$pid/status 的文件
fread(): Unable to read file for /proc/$pid/status
我正在尝试在函数中读取文件 /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] = '[=11=]';
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*
我正在尝试在函数中读取文件 /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] = '[=11=]';
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*