Skip to content

Instantly share code, notes, and snippets.

@fmount
Created October 24, 2017 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmount/0a0acd590b54efb73c2813f063d57736 to your computer and use it in GitHub Desktop.
Save fmount/0a0acd590b54efb73c2813f063d57736 to your computer and use it in GitHub Desktop.
Try to acquire lock on a given resource (file) on fs using the flock
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
int main(int argc, char **argv)
{
int fd;
struct flock fl;
if (argc <= 1) {
printf("Provide at least an argument (file name)\n");
exit(-1);
}
fd = open(argv[1], O_RDWR);
if (fd == -1) {
/* Handle error */;
printf("File doesn't exists\n");
exit(1);
}
/* Make a non-blocking request to place a write lock
* on bytes 100-109 of testfile
* */
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == -1) {
if (errno == EACCES || errno == EAGAIN) {
printf("Already locked by another process\n");
/* We can't get the lock at the moment */
} else {
if (errno == EIO || errno == EBADF)
/* Handle unexpected error */;
printf("I/O Error in locking file [CODE: %d]\n", errno);
}
} else { /* Lock was granted... */
/* Perform I/O on bytes 100 to 109 of file */
printf("Lock on file was granted\n");
/* Unlock the locked bytes */
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == -1)
/* Handle error */;
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment