#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/file.h>

int main() {
    int fd;
    const char *filepath = "test.txt";

    //Si no existe test.txt, lo crea
    fd = open(filepath, O_RDWR | O_CREAT, 0666);
    if (fd == -1) {
        perror("error en open()");
        exit(1);
    }

    printf("Intentando adquirir lock exclusivo sobre [%s]...\n",filepath);
    // Acquire an exclusive lock, blocking until successful
    if (flock(fd, LOCK_EX) == -1) {
        perror("error en flock()");
        close(fd);
        exit(1);
    }

    printf("Lock exclusivo adquirido sobre [%s]!. Mantengo Lock por 20 segundos!...\n",filepath);
    sleep(20);

    printf("Liberando lock exclusivo sobre [%s]...\n",filepath);
    // Release the lock
    if (flock(fd, LOCK_UN) == -1) {
        perror("error en flock() release");
    }

    printf("Lock excluviso liberado!. Cerrando archivo [%s]\n",filepath);
    close(fd);

    return 0;
}
