#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_RDLCK;    /* Type of lock: F_RDLCK, F_WRLCK, F_UNLCK */
    f.l_whence = SEEK_SET;   /* How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END */
    f.l_start = 0L;   /* Starting offset for lock */
    f.l_len = 11L;     /* Number of bytes to lock */
    //           pid_t l_pid;     /* PID of process blocking our lock (set by F_GETLK and F_OFD_GETLK) */
    
    
    printf("Soy el proceso [%d]\n",getpid());
    printf("Intentando adquirir read 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 read lock");
       close(fd);
        exit(1);
    }

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

    printf("Libero read 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;
}
