#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

int main(void) {
    int fd = open("./csie_trains/train_902001", O_RDWR);
    struct flock fl = {
        .l_type = F_RDLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 0};
    // First, check if the file is locked (Assume that fd was opened before
    // here)
    if (fcntl(fd, F_SETLK, &fl) == -1) {
        perror("fcntl F_SETLK");
        exit(69);
    }
    while (1) {
    
    }
    // fl.l_type = F_WRLCK;
    // if (fcntl(fd, F_SETLK, &fl) == -1) {
    //     perror("fcntl F_GETLK");
    //     exit(1);
    // }
    // if (fl.l_type == F_UNLCK) {
    //     // Now try to acquire the lock
    //     fl.l_type = F_WRLCK;
    //     if (fcntl(fd, F_SETLK, &fl) == -1) {
    //         if (errno == EACCES || errno == EAGAIN) {
    //             printf("Failed to acquire lock (already locked)\n");
    //         } else {
    //             perror("fcntl F_SETLK");
    //             exit(1);
    //         }
    //     } else {
    //         fl.l_type = F_UNLCK;
    //         if (fcntl(fd, F_SETLK, &fl) == -1) {
    //             perror("fcntl unlock");
    //             exit(1);
    //         }
    //     }
    // } else {
    //     printf("%d: File is already locked\n", fl.l_pid);
    // }
}
