I've got a project in which I have to use SYS V semaphores. I've got several processes which share a semaphore (using the same key) and initialize it with this code:
bool semaphore_init(semaphore_id_t* sem, int sem_value, key_t key)
{
/* Try to get a semaphore, to check if you will be an owner */
*sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666);
if (*sem == -1)
{
if (errno == EEXIST)
{
/* We are not owners, get semaphore without exclusive flag */
*sem = semget(key, 1, IPC_CREAT | 0666);
if (*sem == -1) return false;
}
else return false;
}
else
{
/* We are owners, initialize semaphore */
int return_value = semctl(*sem , 0, SETVAL, sem_value);
if (return_value == -1) return false;
}
return true;
}
My problem is: I want to remove this semaphore when all processes using it will terminate. Using:
semctl(*sem, 0, IPC_RMID)
is not an option. It deletes semaphore instantly and other processes got undefined behaviour. I just can't find correct way to do it with SYS V API.