#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);
    }

	struct flock f;
	f.l_type =  F_WRLCK;     /* Tipo de lock: F_RDLCK, F_WRLCK, F_UNLCK                       */
    f.l_whence = SEEK_SET;   /* Como interpreto a l_start ?0: SEEK_SET, SEEK_CUR, SEEK_END    */
    f.l_start = 0L;          /* Desplazamiento dentro del archivo a partir de donde comienza
                                el lock                                                       */
    f.l_len = 11L;           /* Cantidad de bytes a lockear!, generalmente equivale al tama#o 
                                registro logico                                               */
    //pid_t l_pid;           
                             /* En miembro l_pid la funcion F_GETLK o F_OFD_GETLK indican el 
                                PID del proceso que tiene un lock sobre el archivo que no es 
                                compatible con lo que pretendemos hacer                       */
                                
    printf("Soy el proceso [%d]\n",getpid());
    printf("Intentando adquirir write lock en bytes 0..10 (11 bytes) del archivo [%s]...\n",filepath);
    // Acquire an exclusive lock, blocking until successful
    if (fcntl(fd,F_SETLK,&f) == -1) {
        perror("error en fcntl() seteando write lock");
        close(fd);
        exit(1);
    }

    printf("Lock adquirido!. Mantengo lock de bytes 0..10 en archivo [%s] por 20 seconds...\n",filepath);
    sleep(20);

    printf("Libero write lock...\n");
    // Release the lock
    f.l_type = F_UNLCK;
    if (fcntl(fd,F_UNLCK,&f) == -1) {
        perror("error fcntl() unlock");
    }

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

    return 0;
}
