Question

i executed the following c code on my ubuntu machine...i have read about fcntl()'s use to lock a file and even reading will not be allowed if F_WRLCK opton is set...so i started this program and before relinquishing the lock by pressing enter i tried to open the file in two ways- by directly double clicking on file1.cpp and by running a different c program in a new terminal...both the time the file was opened...so how did fcntl() allow opening of these files when F_WRLCK is set...

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

struct flock fl = {F_WRLCK, SEEK_SET,   0,      0,     0 };
int fd;

fl.l_pid = getpid();

if ((fd = open("/home/file1.cpp", O_WRONLY)) == -1)
{
    perror("open");
    exit(1);
}


if (fcntl(fd, F_SETLKW, &fl) == -1) 
{
    perror("fcntl");
    exit(1);
}


printf("Press <RETURN> to release lock: ");
getchar();

fl.l_type = F_UNLCK;  /* set to unlock same region */

if (fcntl(fd, F_SETLK, &fl) == -1)
{
    perror("fcntl");
    exit(1);
}

printf("Unlocked.\n");

close(fd);

return 0;
}
Was it helpful?

Solution

fcntl locks are purely advisory locks. Their only effect is to cause fcntl F_SETLK calls to block when the lock cannot be obtained. They have absolutely no effect on IO operations. It's up to your program to obtain the locks it needs before performing IO when synchronization is necessary.

This is completely analogous to using mutexes to protect objects in memory. The mutex will not prevent you from reading or writing memory addresses; it's just a protocol you use to make sure your program only reads and writes and proper times.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top