How to check if a file is locked?

I have the following code where I want to check if a file is locked or not. If not, then I want to write to him. I run this code by running them simultaneously on two terminals, but I always get the status "blocked" every time on both tabs, even if I did not block it. Code below:

#include <fcntl.h> #include <stdio.h> #include <unistd.h> int main() { struct flock fl,fl2; int fd; fl.l_type = F_WRLCK; /* read/write lock */ fl.l_whence = SEEK_SET; /* beginning of file */ fl.l_start = 0; /* offset from l_whence */ fl.l_len = 0; /* length, 0 = to EOF */ fl.l_pid = getpid(); /* PID */ fd = open("locked_file", O_RDWR | O_EXCL | O_CREAT); fcntl(fd, F_GETLK, &fl2); if(fl2.l_type!=F_UNLCK) { printf("locked"); } else { fcntl(fd, F_SETLKW, &fl); /* set lock */ write(fd,"hello",5); usleep(10000000); } printf("\n release lock \n"); fl.l_type = F_UNLCK; fcntl(fd, F_SETLK, &fl); /* unset lock */ } 
+5
source share
2 answers

Very simple, just run fnctl with F_GETLK instead of F_SETLK. This will set the data in your pointer to the current state of the lock, you can see if it will be locked, and then access the l_type property.

see below http://linux.die.net/man/2/fcntl .

+4
source

You also need fl2 be memset equal to 0. Otherwise, when using fcntl(fd, F_GETLK, &fl2) and perror on failure, you will see a message on it as such:

fcntl: Invalid Deviation

I recommend using perror when debugging system calls.

+1
source

Source: https://habr.com/ru/post/983839/


All Articles