c - Unnamed semaphore POSIX IPC -
i allocated shared memory segment of size of integer.
the expected outcome on stdout should be:
p: 1 c: 2
but instead is:
c: 1 p: 2
why child process not being blocked until parent done , has unlocked 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 processes, =0 threads int value = 1; // number of processes @ time sem_init(&sem, pshared, value); // initialize 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 fork()."); exit(exit_failure); }
compiled with:
gcc -o executable sem.c -pthread
the sem_t
must in shared memory if "pshared".
struct my_shared_mem { sem_t sem; int value; }; ... later ... struct my_shared_mem *shared; shmid = shmget(ipc_private, sizeof(*shared), ...); shared = shmat(shmid, ...); shared->value = 0; sem_init(&shared->sem, 1, 1); ...
Comments
Post a Comment