Reputation: 31
Good day.
Im creating a multi-thread program which will be reading a basic date about process which you will point using PID number.
And one of the threads should read information from "status
" file. This file is in /proc/NUMBER_PID/status
So I wrote this pthread
function. But Im still geting an error. Can anyone point where is the problem ?
pthread_create(&pth[1],NULL,odczyt,&pid);
.....
##define NUMBER arg
void *odczyt(void*arg)
{
char*bufor;
FILE *plik;
plik=fopen("/proc/NUMBER/status","r");
if(plik==0){
perror("Error: Blad otwarcia pliku");
exit(1);
}
while((fgets(bufor,200,plik))!=0)
{
printf("%s",bufor);
}
fclose(plik);
free(bufor);
}
Upvotes: 1
Views: 71
Reputation: 1
This line is wrong (read carefully proc(5)...)
plik=fopen("/proc/NUMBER/status","r");
You probably want (if you care about your own process):
plik = fopen("/proc/self/status", "r");
if (!plik) {perror("/proc/self/status"); exit(EXIT_FAILURE); }
(the failure of above fopen
is unlikely, but could happen if you are out of file descriptors)
or, if you care about some other process of given pid
(declared as pid_t pid;
and suitably computed), you need to computer a string (e.g. pathname
in below code chunk) containing the appropriate path (what a shell would expand from /proc/$pid/status
; read about globbing):
char pathname[80];
snprintf(pathname, sizeof(pathname), "/proc/%d/status", (int)pid);
plik = fopen(pathname, "r");
if (!plik) {perror(pathname); exit(EXIT_FAILURE); }
Compile your code with all warnings & debug info (e.g. gcc -Wall -Wextra -g
) then use the debugger (gdb
)
(you really need to know how to use the debugger, so take several hours or days to learn how to use gdb
)
Upvotes: 0
Reputation: 22372
You have a lot of issues in your code,
##define NUMBER arg
/* ^^^^^^^^^^^^^^^^^^^ what is this define? */
void *odczyt(void*arg)
{
char*bufor;
/*^^^^^^^^^^^^ this is never malloc'd */
FILE *plik;
plik=fopen("/proc/NUMBER/status","r");
/* you never use ^^^^^^^^ the pid */
you are not replacing the number with the PID
if(plik==0){
perror("Error: Blad otwarcia pliku");
exit(1);
}
while((fgets(bufor,200,plik))!=0)
{
printf("%s",bufor);
}
fclose(plik);
free(bufor);
/* ^^^^^^^^^^^ free'ing something you never malloc'd */
}
try:
void *odczyt(void*arg)
{
char bufor[256];
FILE *plik;
char statusFile[256];
snprintf(statusFile, sizeof(statusFile), "/proc/%u/status", *(pid_t *)arg));
plik=fopen(filename,"r");
if(!plik){
perror("Error: Blad otwarcia pliku");
exit(1);
}
while((fgets(bufor, sizeof(bufor),plik))!=0)
{
printf("%s",bufor);
}
fclose(plik);
}
Upvotes: 1
Reputation: 634
You are trying to open file /proc/arg/status
, because you use processor to create path. You should to put pid in path in runtime using e,g sprintf
Upvotes: 0