I have issues understanding how to share a POSIX semaphore among multiple processes. I am trying to do the following:
1. The producer initializes a semaphore
2. The producer posts 10 tokens to the semaphore and sleeps 1 second before doing so
3. The consumer gets a token from the semaphore
When I start my producer, a segmentation fault (core dumped) occurs. Furthermore I am not sure, if my way of sharing the named semaphore is correct.
Producer:
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#define SEM_NAME "/mutex"
int main () {
sem_t* sem = sem_open(SEM_NAME,O_CREAT,0644,0);
for (int i = 0; i<10; i++) {
sleep(1);
sem_post(sem);
printf("Token was posted! \n");
}
sem_close(sem);
sem_unlink(SEM_NAME);
}
Consumer:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <fcntl.h>
int main () {
sem_t *mutex = sem_open("/mutex",O_CREAT);
for(int i = 0; i<10; i++) {
sem_wait(mutex);
printf("One Token was consumed! %d",(int) getpid());
}
sem_close(mutex);
}
Make your consumer wait :
sem_wait(mutex);
and flush each print (if not prints may all be flushed at the end):
print("One token consumed\n");
Also; please take care of returned value from open:
if (mutex==SEM_FAILED) exit(1);
and
if (sem==SEM_FAILED) exit(1);