I am creating a multi-process application with a shared memory segment and a semaphore locking it and signal handlers.
Whenever I lock and unlock my semaphore everything is ok, as long as it is in my main program (or one of the children).
The problem occurs when I am inside a signal handler. There I lock the semaphore, do some updates on the shared memory segment and unlock it.
I have a struct sembuf
let's call it sb
.
My lock code
void semLock(){
sb.sem_op=-1;
semop(sID,sb,sizeof(sb);
}
my unlock code
void semUnlock(){
sb.sem_op=1;
semop(sID,sb,sizeof(sb);
}
and how I do my stuff
void signalHandler(int segnum){
semLock();
//do some stuff
semUnlock();
}
There is no real reason why this would not work as sID
is global and is inherited to all the children the parent process creates and also when the children are running other code that locks and unlocks the semaphore.
I think the issue is that this is inside a signal handler but I do not understand why. The error that is printed in the terminal is
semop failed identifier removed
I try googling the error but did not find any meaningful or relevant information on what might cause it.
EDIT
when I create sb
it's initialized with {0,-1,0}
I only have one semaphore in my ipcs
As it turns out somewhere in my code I was losing the semaphore ID and semLock and semUnlock were trying to lock and unlock a wrong ID and they were returning an error