#include <stdio.h>
#include <sys/fcntl.h>

main(int argc, char *argv[]) {
  int fd;
  char *fname = argv[1];
  struct flock fl = { 0 };
  int r;

  printf("Trying to lock %s..\n", fname);

  fd = open(fname, O_RDWR);
  if(fd < 0) {
    perror("opening file");
    return;
  }

  fl.l_type = F_WRLCK;
  r = fcntl(fd, F_SETLK, &fl);

  if(r < 0) {
    perror("locking file");
    return;
  }

  printf("Lock successful, waiting 5 seconds..\n");

  sleep(5);
  printf("Trying to unlock..\n");

  fl.l_type = F_UNLCK;
  r = fcntl(fd, F_UNLCK, &fl);

  if(r < 0) {
    perror("unlocking file");
    return;
  }

  printf("Unlocked.\n");
  close(fd);
}

