相关疑难解决方法(0)

检查文件是否已使用flock()锁定?

我有一个我正在写的文件,但我需要先锁定它(使用flock()),以防止任何其他脚本写入它.所以我有:

$file=fopen($file_p);

if (flock($file, LOCK_EX)) {//lock was successful
    fwrite($file,$write_contents);          
}
Run Code Online (Sandbox Code Playgroud)

但我需要检查它是否已被锁定,以防止其他脚本写入它.

我怎样才能做到这一点?

php flock

7
推荐指数
2
解决办法
8950
查看次数

如何检查文件是否被锁定?

我有以下代码,我想检查文件是否被锁定.如果没有,那么我想写信给它.我通过在两个终端上同时运行它来运行此代码但是我每次都在两个选项卡中都处于"锁定"状态,即使我没有锁定它.代码如下:

#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); …
Run Code Online (Sandbox Code Playgroud)

c locking file fcntl

6
推荐指数
1
解决办法
4811
查看次数

标签 统计

c ×1

fcntl ×1

file ×1

flock ×1

locking ×1

php ×1