volanin
June 23rd, 2007, 05:29 PM
Hello guys.
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.)
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
int main( void )
{
sem_t *sem;
sem = sem_open( "/MySemaphore", O_CREAT, 0666, 1 );
for(;;)
{
sem_wait( sem );
printf( "Semaphore locked!\n" );
sleep( 5 );
sem_post( sem );
printf( "Semaphore unlocked!\n\n" );
sleep( 1 );
}
return 0;
}
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.
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')
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.)
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
int main( void )
{
sem_t *sem;
sem = sem_open( "/MySemaphore", O_CREAT, 0666, 1 );
for(;;)
{
sem_wait( sem );
printf( "Semaphore locked!\n" );
sleep( 5 );
sem_post( sem );
printf( "Semaphore unlocked!\n\n" );
sleep( 1 );
}
return 0;
}
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.
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')