I am having a hard time with the behaviour of POSIX semaphores.
Please, take a look at the following code: (Error checking omitted for the sake of simplicity.)
As you can see, this code creates a POSIX named semaphore (or connects to one if the semaphore has already been created by another process), and start to continuously lock it for 5 seconds, and then unlock it. The desired effect is that two or three instances of this program running concurrently will alternate the lock.
int main( void )
sem = sem_open( "/MySemaphore", O_CREAT, 0666, 1 );
sem_wait( sem );
printf( "Semaphore locked!\n" );
sleep( 5 );
sem_post( sem );
printf( "Semaphore unlocked!\n\n" );
sleep( 1 );
The problem is:
If one instance of the program dies (or is explicitly killed) while it has the lock, IT DOES NOT UNDO THE LOCK, and the other program instances will wait for the lock forever. This effectvely makes the semaphore useless, since it is locked forever and any new instances of the program will already start deadlocked. This behaviour does not happen with System V semaphores, which undo the lock automatically. Is this a limitation of POSIX semaphores, or am I doing something wrong?
Hope you can help, this has been bugging me for days.
Thank you a lot.
(To compile this you have to link against libpthread: 'gcc code.c -lpthread')