#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 saber si puedo 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_GETLK,&f) == -1) {
        perror("error en fcntl() preguntando x read lock");
		close(fd);
        exit(1);
    }

    if ( f.l_type == F_UNLCK ) {
		printf("No hay problema en poner read lock en bytes 0..10 de archivo [%s]\n",filepath);
	} else {
		printf("Rayos!, No puedo poner read lock en bytes 0..10 de archivo [%s]\n",filepath);
		printf("Debido a que el proceso [%d] tiene lock [%d] de [%ld] bytes, a partir de posicion [%ld]\n",
			f.l_pid,f.l_type,f.l_len,f.l_start);
		printf("Lock de tipo F_RDLCK=%d, F_WRLCK=%d, F_UNLCK=%d\n",F_RDLCK,F_WRLCK,F_UNLCK);
	}

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

    return 0;
}
