I am trying to read the file /proc/$pid/status
in a function. I am able to open the file using fopen
and when I read it using fread()
I get Segmentation fault (core dumped)
.
Function:
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);
}
And here is the output which I obtain:
Pid of the process is: 85244
Path: /proc/85244/status
File pointer not null
Size of buffer: 3000
Segmentation fault (core dumped)
The buffer
size has been allocated properly and also the fp
is not null. I have similar functionalities in other areas of my code and they work fine. I have checked the signature of fread()
and that looks fine too.
Can someone help me understand the issue behind this?
The issue is in your getFile()
function. The rest of the code is OK.
I suspect you're returning an invalid FILE*
from getFile()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.