I am trying to emulate callback mechanism in C. The code I have is follows:
Code:
#include <stdio.h>
#include <pthread.h>
struct fopen_struct {
char *filename;
char *mode;
void *(*callback) (FILE *);
};
void *fopen_callback(FILE *);
pthread_t fopen_t(void *(*callback)(FILE *), const char *, const char *);
void *__fopen_t__(void *);
pthread_t fopen_t(void *(*callback)(FILE *), const char *filename, const char *mode) {
struct fopen_struct args;
args.filename = filename;
args.mode = mode;
args.callback = callback;
pthread_t thread;
pthread_create(&thread, NULL, &__fopen_t__, &args);
//pthread_join ??
return thread;
}
void *__fopen_t__(void *ptr) {
printf("I am done!\n");
struct fopen_struct *args = (struct fopen_struct *)ptr;
FILE *result = fopen(args -> filename, args -> mode);
args -> callback(result);
}
int main() {
pthread_t thread = fopen_t(&fopen_callback, "test.txt", "r");
printf("abc\n");
//pthread_join ??
}
void *fopen_callback(FILE *stream) {
if (stream != NULL)
printf("Opened file successfully\n");
else
printf("Error\n");
}
If I do a pthread_join in fopen_t() it works perfectly fine. But if I do that in main() I get a segmentation fault error. I want to call it in main() because I want it to be non-blocking, is there any solution?