Cannot lock a specific file type in C

62 Views Asked by At

I am new to C and programming in general. I have created a program where it will try to lock the file I input on the terminal and I want to lock the GCC compiled file, "lockDemo", but it does not work because whenever I open another terminal to lock the file, the process does not get blocked.

gcc-o lockDemo lockdemo.c

However, if I try to lock the uncompiled C file, "lockdemo.c", it works as intended. e.g, if I lock the lockdemo.c file in the first terminal and I try to lock it again in a second terminal, the process is blocked until the lock is released in the first terminal.

Why can't I lock the compiled file?

my code

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main (int argc, char* argv[])
{
    char* file = argv[1];
    int fd;
    struct flock lock;

    //Open file descriptor
    fd = open (file, O_WRONLY);
        
    printf ("Press <ENTER> to lock\n");
    getchar();

    printf("Trying to get lock...");
    //Initialize lock struct
    memset (&lock, 0, sizeof(lock));
    lock.l_type = F_WRLCK;
    //Set a lock to the file
    fcntl (fd, F_SETLKW, &lock);
    printf("got lock\n");

    printf ("Press <ENTER> to release lock\n");
    getchar ();

    
    //Relase lock
    lock.l_type = F_UNLCK;
    fcntl (fd, F_SETLKW, &lock);
    printf ("Unlocked\n");

    close (fd);
    return 0;
}
0

There are 0 best solutions below