Emp*_*uin 6 c locking file fcntl
我有以下代码,我想检查文件是否被锁定.如果没有,那么我想写信给它.我通过在两个终端上同时运行它来运行此代码但是我每次都在两个选项卡中都处于"锁定"状态,即使我没有锁定它.代码如下:
#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 */
}
Run Code Online (Sandbox Code Playgroud)
非常简单,只需使用 F_GETLK 而不是 F_SETLK 运行 fnctl 即可。这会将指针处的数据设置为锁的当前状态,您可以通过访问 l_type 属性来查找它是否被锁定。
详细信息请参见: http: //linux.die.net/man/2/fcntl 。
| 归档时间: |
|
| 查看次数: |
4811 次 |
| 最近记录: |