The sample code here demonstrates the following techniques:
- The use of POSIX
fcntl()to perform file locking - The realization of mutual exclusion via file locking
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define LOCK_FILENAME "/tmp/lock_filename"
int main(int argc, char *argv[])
{
int fd;
struct flock flock_lock, flock_unlock;
/*--------------------------------*/
/* Initialization */
/*--------------------------------*/
/* Create the lock file if it's not there yet */
if ((fd = open(LOCK_FILENAME, O_CREAT | O_WRONLY, (mode_t) S_IWUSR)) < 0) {
if (errno == EEXIST) {
if ((fd = open(LOCK_FILENAME, O_RDWR)) < 0) {
return EXIT_FAILURE;
}
}
else {
return EXIT_FAILURE;
}
}
/* Miscellaneous */
flock_lock.l_type = F_WRLCK;
flock_lock.l_whence = SEEK_SET;
flock_lock.l_start = 0;
flock_lock.l_len = 0;
flock_unlock.l_type = F_UNLCK;
flock_unlock.l_whence = SEEK_SET;
flock_unlock.l_start = 0;
flock_unlock.l_len = 0;
/*--------------------------------*/
/* Mutual Exclusion */
/*--------------------------------*/
/* Lock the file */
while (fcntl(fd, F_SETLKW, &flock_lock) < 0) {
// errno is set appropriately
if (errno == EINTR)
continue;
else
return EXIT_FAILURE;
}
/* Critical section! */
puts("Critical section");
/* Unlock the file */
if (fcntl(fd, F_SETLKW, &flock_unlock) < 0) {
// errno is set appropriately
return EXIT_FAILURE;
}
// End of mutual exclusion
return EXIT_SUCCESS;
}
Notes:
- When any file descriptor for a file is closed, all locks that the process holds on that file are also released.
- Locks are automatically released when a process exits.
- Locks are not inherited by
fork()-ed children.
Bookmark/Search this post with:

Digg
Facebook
Google
Yahoo
Technorati