Search code examples
cmacosfile-lockingflock

flock() doesn't preventing other process to get exclusive lock


I wrote a simple code to test the flock():

int main (int argc, char * const argv[]) {

    int fd1;

    if (fd1 = open( "file1", O_RDWR | O_CREAT | O_TRUNC) == -1)
    {
        perror("Cannot open file 1.\n");
        fflush(stdout);
    }
    else
    {
        printf("file opened 1.\n");
        fflush(stdout);
    }

    if(flock(fd1,LOCK_EX)==0)
    {
        printf("THE FILE WAS LOCKED 1.\n");
    }
    else if(errno == EACCES)
    {
        printf("The file is locked 1.\n");
    }

    std::cout<<"Enter any key:"<<std::endl;
std::cin >> input;

    close(fd1);
    std::cout<<"Lock was released."<<std::endl;

    return 0;
}

When I run the executable 'Alex' twice :

1st process:

$ ./Alex 
file opened 1.
THE FILE WAS LOCKED 1.
Enter any key:

2nd process:

$ ./Alex 
file opened 1.
THE FILE WAS LOCKED 1.
Enter any key:

In activity monitor i see two instances of Alex with two different PIDs.

It seems like flock() doesn't work. What am I missing? Thanks!


Solution

  • Try:

    if ((fd1 = open( "file1", O_RDWR | O_CREAT | O_TRUNC)) == -1)
    //  ^                                                ^
    

    As what you have written is the same as:

    if (open( "file1", O_RDWR | O_CREAT | O_TRUNC) == -1)
        fd1 = TRUE;
    else
        fd1 = FALSE;
    

    Therefore you are attempting to lock stdin or stdout (depending on the result of open()).