如何检查,如果一个文件被锁定或没有? [英] How to check if a file is locked or not?

查看:223
本文介绍了如何检查,如果一个文件被锁定或没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,我想检查,如果文件被锁定或没有。如果没有,那么我想写它。我通过在两个终端同时运行它们运行此code,但我总是在这两个标签,每一次,即使我没有锁上了锁定状态。在code是如下:

 的#include< fcntl.h>
#包括LT&;&stdio.h中GT;
#包括LT&;&unistd.h中GT;诠释的main()
{
    结构涌向佛罗里达州,FL2;
    INT的fd;    fl.l_type = F_WRLCK; / *读/写锁定* /
    fl.l_whence = SEEK_SET; / * *文件的开头/
    fl.l_start = 0; / *从l_whence偏移* /
    fl.l_len = 0; / *长度,0 =为EOF * /
    fl.l_pid = GETPID(); / * * PID /    FD =打开(locked_file,O_RDWR | O_EXCL | O_CREAT);
    使用fcntl(fd,F_GETLK,&安培; FL2);
    如果(fl2.l_type!= F_UNLCK)
    {
        的printf(锁定);
    }
    其他
    {
        使用fcntl(fd,F_SETLKW,&安培; FL); / *设置锁定* /
        写(FD,你好,5);
        usleep(10000000);
    }
    的printf(\\ n释放锁\\ n);    fl.l_type = F_UNLCK;
    使用fcntl(fd,F_SETLK,&安培; FL); / *取消设置锁定* /
}


解决方案

很简单,只需要运行fnctl与F_GETLK,而不是F_SETLK。这将在您的指针锁的当前状态设置的数据,你可以看看,如果它是通过访问L_TYPE属性锁定,那么。

请参阅: http://linux.die.net/man/2/fcntl了解详情。

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 */
}

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.

这篇关于如何检查,如果一个文件被锁定或没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆