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

707 views Asked by At

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!

2

There are 2 answers

0
trojanfoe On BEST ANSWER

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()).

0
nos On

Your line

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

has 2 bugs

  1. You're assigning the result of open( "file1", O_RDWR | O_CREAT | O_TRUNC) == -1 to fd1, which likely is false (0), so you are passing 0 to flock(). Use

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

  2. When passing the O_CREAT flag to open, you need to pass in the permissions in a 3. argument, so e.g.

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