07-20-07 06:20 PM
Ravi <ra.ravi.rav@gmail.com> writes:
> #include <stdio.h>
> #include <pthread.h>
> pthread_key_t pkt_fp;
> void *thread_start(void *v)
> {
> FILE *fp;
> char fname[30];
> sprintf(fname,"x%p",pthread_self());
> pthread_setspecific(pkt_fp,fp);
> fp = fopen(fname,"w");
> fprintf(fp,"This is the thread with ID %p",pthread_self());
> fflush(fp);
> return NULL;
> }
>
> void clean_up(void *v)
> {
> fclose((FILE *)v);
> }
>
> int main(void)
> {
> pthread_t tid1, tid2;
> pthread_key_create(&pkt_fp,clean_up);
> pthread_create(&tid1,NULL,&thread_start,NULL);
> pthread_create(&tid2,NULL,&thread_start,NULL);
> pthread_join(tid1,NULL);
> pthread_join(tid2,NULL);
> }
> I inspected the above code and it gives segmentation fault at fclose
> in the function void clean_up(). Can you please help me know why this
> is happening?
By the time you set the key value, the value of 'fp' is
indeterminate, because it hasn't yet been set to a valid value.
[ Post a follow-up to this message ]
|