Windows has an option to open a file with exclusive access rights. Unix doesn\'t.
In order to ensure exclusive access to some file or device, it is common practice
The answer of Hasturkun is the one that has put me on track.
Here is the code I use
#include
#include
#include
#include
/*! Try to get lock. Return its file descriptor or -1 if failed.
*
* @param lockName Name of file used as lock (i.e. '/var/lock/myLock').
* @return File descriptor of lock file, or -1 if failed.
*/
int tryGetLock( char const *lockName )
{
mode_t m = umask( 0 );
int fd = open( lockName, O_RDWR|O_CREAT, 0666 );
umask( m );
if( fd >= 0 && flock( fd, LOCK_EX | LOCK_NB ) < 0 )
{
close( fd );
fd = -1;
}
return fd;
}
/*! Release the lock obtained with tryGetLock( lockName ).
*
* @param fd File descriptor of lock returned by tryGetLock( lockName ).
* @param lockName Name of file used as lock (i.e. '/var/lock/myLock').
*/
void releaseLock( int fd, char const *lockName )
{
if( fd < 0 )
return;
remove( lockName );
close( fd );
}