I allocated a shared memory segment of the size of an integer.
The expected outcome on stdout should be:
P: 1
C: 2
But instead it is:
C: 1
P: 2
Why is the child process not being blocked until parent is done and has unlocked the shared memory segment?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <semaphore.h>
#define SHMSEGSIZE sizeof(int)
int main(void){
pid_t pid;
int shmID;
int *shared_mem;
/* initializing shared memory */
shmID = shmget(IPC_PRIVATE, SHMSEGSIZE, IPC_CREAT | 0644);
shared_mem = (int *)shmat(shmID, 0, 0);
*shared_mem = 0;
/* initializing semaphore */
sem_t sem;
int pshared = 1; // !=0 for processes, =0 for threads
int value = 1; // number of processes at a time
sem_init(&sem, pshared, value); // initialize the semaphore
pid = fork();
if(pid>(pid_t)0){ // parent
sem_wait(&sem);
sleep(6);
*shared_mem += 1;
printf("P: %d\n", *shared_mem);
sem_post(&sem);
exit(EXIT_SUCCESS);
} // parent
if(pid==(pid_t)0){ // child
sleep(3);
sem_wait(&sem);
*shared_mem += 1;
sem_post(&sem);
printf("C: %d\n", *shared_mem);
exit(EXIT_SUCCESS);
} // child
/* fork() failed */
printf("Failed to fork().");
exit(EXIT_FAILURE);
}
Compiled with:
gcc -o executable sem.c -pthread