#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>

#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000

int main(int argc, char **argv)
{
    int fd1, fd2, i;
    if (argc < 3) {
        fprintf(stderr, "No argument specified\n");
        return 1;
    }
    fd1 = open(argv[1], O_RDWR|O_CREAT, 0666);
    if (fd1 == -1) {
        perror(argv[1]);
        return 2;
    }
    fd2 = open(argv[2], O_RDWR|O_CREAT, 0666);
    if (fd2 == -1) {
        perror(argv[2]);
        return 2;
    }
    for (i = 0; ; i++) {
        flock(fd2, LOCK_EX);
        printf("%d Getting %s lock ... ", i, "exclusive");
        fflush(stdout);
        flock(fd1, LOCK_EX);
        printf("got it\nNow sleeping\n");
        usleep(LOCKED_SLEEP);
        printf("%d Releasing %s lock ... ", i, "exclusive");
        fflush(stdout);
        flock(fd1, LOCK_UN);
        flock(fd2, LOCK_UN);
        printf("done\nNow sleeping\n");
        usleep(UNLOCKED_SLEEP);
    }
}

