I'm looking for help with synchronization problem in Linux. I'm newbie, and I think I don't really understand how to use semaphores to synchronize. My task is to sync two processes that access a file - one reads from fifo from another process, writes to this file, then another reads. I know that my code lacks synchronization, but i have no clue how to do this.
Code:
sem_t writer, reader;
void readFromFifoSendToFile(void) {
sem_init(&writer, 1, 1);
FILE *fp;
char buffer[100];
FILE *file;
file = fopen("file", "w+");
fclose(file);
while(1) {
sem_wait(&writer);
fp = fopen("fifo", "r");
fscanf(fp, "%s", buffer);
fclose(fp);
file = fopen("file", "a+");
fputs(buffer, file);
fclose(file);
sem_post(&writer);
}
}
void readFromFileAndPrint(void) {
sem_init(&reader, 1, 1);
FILE *fp;
char buffer[100];
int counter = 0;
while(1) {
sem_wait(&reader);
counter++;
if(counter == 1) {
sem_wait(&writer);
sem_post(&reader);
fp = fopen("file", "r");
fscanf(fp, "%s", buffer);
fclose(fp);
printf("%s", buffer);
sem_wait(&reader);
if(counter == 0) {
sem_post(&writer);
}
sem_post(&reader);
}
}