I am working on a project that requires process synchronization. The problem I have is that the samaphore I use does not seem to be shared across all processes. It behaves similar to local variable. This is a simplified code, but demonstrates the same problem:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
#include <fcntl.h>
sem_t sem_1; //Global variable (semaphore).
int main(){
sem_init(&sem_1, 1, 0); //semaphore starts with 0
pid_t child_pid_or_zero = fork(); //process fork
if (child_pid_or_zero < 0){
perror("fork() error");
exit (2);
}
if (child_pid_or_zero != 0){
sem_wait(&sem_1); //decrement to -1 and waits
printf("I am the parent %d, my child is %d.\n",getpid(),child_pid_or_zero);
}else{
printf("i am child\n");
sem_post(&sem_1); //increments
}
return 0;
}
The parent process never gets over the wait signal. I tried adding mupltiple sem_post() to both processes and print the values with sem_getvalue() and the numbers printed seemed not to be shared (every processs incremented its own semaphore).
Thanks for help.