Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is locked or not?

I have the following code where I want to check if the file is locked or not. If not then I want to write to it. I am running this code by running them simultaneously on two terminals but I always get "locked" status every time in both tabs even though I haven't locked it. The code is 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 */
}
like image 831
Emperor Penguin Avatar asked Feb 20 '14 19:02

Emperor Penguin


People also ask

How do you tell if a file is locked in Windows?

In the Resource Monitor window, go to the CPU tab and expand the Associated Handles option. Now, in the search box, type the name of the file that is showing locked by a process and press Enter button. It will show you a list of processes holding the target file.

Which files are locked?

A computer file that can be used by only a single program or process at one time is considered a locked file. In other words, the file in question is "locked away" from being used by any other program on the computer it's on or even over a network. All operating systems use locked files.

How can I tell if a file is locked in powershell?

File]::OpenWrite((Resolve-Path $file). Path). close() , otherwise it will default to the home directory and become a hard to debug logic error. Note that this returns false if the file is locked, while @Dech's answer returns true if the file is locked.

How do you unlock a file?

Right-click on the file. In the menu that appears, select Lock File. To unlock, right-click the file and select Unlock File.


2 Answers

Very simple, just run fnctl with F_GETLK instead of F_SETLK. That will set the data at your pointer to the current state of the lock, you can look up if it is locked then by accessing the l_type property.

please see: http://linux.die.net/man/2/fcntl for details.

like image 126
Vality Avatar answered Oct 14 '22 20:10

Vality


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

fcntl: Invalid Arguement

I recomend that you use perror, when debugging system calls.

like image 24
HSchmale Avatar answered Oct 14 '22 20:10

HSchmale