this does not take your code into account, but I had the same problem in reading Reader (operating systems) http://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem .
This is due to the fact that the file pointer is global, so whenever a reader tried to read, but in b / w another reading reads and closes the file pointer, therefore, when another reader who has not finished reading, tried close the file pointer after reading. therefore, it happened that the file pointer is already closed, it does not point to any file. The solution I used. Instead of declaring a pointer to a global file, I declared it local to the reader function that he or you can check the file pointer for NULL, and if NULL, do not close the file pointer.
#include<stdio.h> #include<semaphore.h> #include<pthread.h> #include<string.h> #include<stdlib.h> sem_t x,wsem; int rc=0; char ch; char str[20]; void *reader(void *); void *writer(void *); int main() { int nw,nr,i=0,j=0; pthread_t w[10],r[10]; sem_init(&x,0,1); sem_init(&wsem,0,1); rc=0; printf("Enter the no of readers:"); scanf("%d",&nr); printf("Enter the no of writers"); scanf("%d",&nw); while(i<nw || j<nr) { if(i<nw) { pthread_create(&w[i],NULL,writer,(void *)i); i++; } if(j<nr) { pthread_create(&r[j],NULL,reader,(void *)j); j++; } } for(i=0;i<nw;i++) { pthread_join(w[i],NULL); } for(j=0;j<nr;j++) { pthread_join(r[j],NULL); } return 0; } void *reader(void *arg) { FILE *fptr; sem_wait(&x); rc++; if(rc==1) sem_wait(&wsem); sem_post(&x); printf("\nreader %d:",arg); fptr=fopen("temp.txt","r+"); while(fgets(str,10,fptr)!=NULL) { printf("%s",str); } printf("\n"); fclose(fptr); sem_wait(&x); rc--; if(rc==0) sem_post(&wsem); sem_post(&x); } void *writer(void *arg) { FILE *fptr1; sem_wait(&wsem); printf("\nwriter-%d:\n",arg); fptr1=fopen("temp.txt","a+"); printf("enter the string:"); scanf("%s",str); fputs(str,fptr1); fclose(fptr1); sem_post(&wsem); }