I have a problem with semaphore and fork in Linux, here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <unistd.h>
#define KEY 464
void debug(int semafor_id) {
printf("Value of sem 0 is: %d \n", semctl (semafor_id, 0 , GETVAL , 0));
}
void main()
{
int id;
struct sembuf operations[1];
// Sreate semaphore
id = semget(KEY, 1, 0777 | IPC_CREAT );
// set value
operations[0].sem_num = 0;
operations[0].sem_op = 10;
operations[0].sem_flg = 0;
semop(id, operations, 1);
// show what is the value
debug(id);
// do the same with the child process
if(!fork()) {
printf("IN child process \n");
debug(id);
exit(0);
}
semctl (id, 0 , IPC_RMID , 0);
}
The output is:
- Value of sem 0 is: 10
- IN child process:
- value of sem 0 is: -1
So it seems I can’t use semaphore in child process. I don’t think I need to use shared memory. Help?
You have a race condition there.
If the parent continues executing after the
fork, before the child gets a chance to run, then the parent will destroy the semaphore before the child can inspect its value.Add a pause of some sort, or better use
wait, in the parent before you destroy the semaphore and/or usestrerrorto figure out what the exact error is in the child.