我有一个我正在写的文件,但我需要先锁定它(使用flock()),以防止任何其他脚本写入它.所以我有:
$file=fopen($file_p);
if (flock($file, LOCK_EX)) {//lock was successful
fwrite($file,$write_contents);
}
Run Code Online (Sandbox Code Playgroud)
但我需要检查它是否已被锁定,以防止其他脚本写入它.
我怎样才能做到这一点?
我有以下代码,我想检查文件是否被锁定.如果没有,那么我想写信给它.我通过在两个终端上同时运行它来运行此代码但是我每次都在两个选项卡中都处于"锁定"状态,即使我没有锁定它.代码如下:
#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)