The sample code here demonstrates the following techniques:
fcntl() to perform 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:
fork()-ed children.