Skip to content

Instantly share code, notes, and snippets.

@antirez
Created April 24, 2014 13:42
Show Gist options
  • Save antirez/11255064 to your computer and use it in GitHub Desktop.
Save antirez/11255064 to your computer and use it in GitHub Desktop.
lock_test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>
#include <errno.h>
void lockFile(char *filename) {
int fd;
/* To lock it, we need to open the file in a way it is created if
* it does not exist, otherwise there is a race condition with other
* processes. */
fd = open(filename,O_WRONLY|O_CREAT,0644);
if (fd == -1) {
perror("Can't open the file in order to acquire a lock");
exit(1);
}
if (flock(fd,LOCK_EX|LOCK_NB) == -1) {
if (errno == EWOULDBLOCK) {
printf("Sorry, this file is already locked by another process.\n");
} else {
perror("flock error");
}
exit(1);
}
/* Note: leak the 'fd' by not closing it, so that we'll retain the
* lock to the file as long as the process exists. */
printf("Lock acquired!\n");
}
int main(void) {
char *filename = "/tmp/foo.txt";
lockFile(filename);
while(1) {
int fd = open(filename,O_WRONLY|O_CREAT,0644);
int len;
char buf[32];
if (fd == -1) {
perror("Can't open the file for writing");
exit(1);
}
len = snprintf(buf,sizeof(buf),"%d", rand());
write(fd,buf,len);
ftruncate(fd,len);
close(fd);
sleep(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment