linux系统编程之struct flock 结构体

该结构是在lock.h文件中定义。

lock.h File

 

功能

定义一些文件的锁的选项

Description

The flock structure in the /usr/include/sys/flock.h file, which describes a lock, contains the following fields:

 

l_type Describes the type of lock. If the value of the Command parameter to the fcntl subroutine is F_SETLK orF_SETLKW, the l_type field indicates the type of lock to be created. Possible values are:
F_RDLCK
A read lock is requested.
F_WRLCK
A write lock is requested.
F_UNLCK
Unlock. An existing lock is to be removed.

If the value of the Command parameter to the fcntl subroutine is F_GETLK, the l_type field describes an existing lock. Possible values are:

F_RDLCK
A conflicting read lock exists.
F_WRLCK
A conflicting write lock exists.
F_UNLCK
No conflicting lock exists.
l_whence Defines the starting offset. The value of this field indicates the point from which the relative offset, the l_startfield, is measured. Possible values are:
SEEK_SET
The relative offset is measured from the start of the file.
SEEK_CUR
The relative offset is measured from the current position.
SEEK_END
The relative offset is measured from the end of the file.

These values are defined in the unistd.h file.

l_start Defines the relative offset in bytes, measured from the starting point in the l_whence field.
l_len Specifies the number of consecutive bytes to be locked.
l_sysid Contains the ID of the node that already has a lock placed on the area defined by the fcntl subroutine. This field is returned only when the value of the Command parameter is F_GETLK.
l_pid Contains the ID of a process that already has a lock placed on the area defined by the fcntl subroutine. This field is returned only when the value of the Command parameter is F_GETLK.

l_vfs

Specifies the file system type of the node identified in the l_sysid field.

 

 

看一下示例吧!

int
waldirlock(Wal *w)
{
    int r;
    int fd;
    struct flock lk;
    char path[PATH_MAX];

    r = snprintf(path, PATH_MAX, "%s/lock", w->dir);
    if (r > PATH_MAX) {
        twarnx("path too long: %s/lock", w->dir);
        return 0;
    }

    fd = open(path, O_WRONLY|O_CREAT, 0600);
    if (fd == -1) {
        twarn("open");
        return 0;
    }

    lk.l_type = F_WRLCK;
    lk.l_whence = SEEK_SET;
    lk.l_start = 0;
    lk.l_len = 0;
    r = fcntl(fd, F_SETLK, &lk);
    if (r) {
        twarn("fcntl");
        return 0;
    }

    // intentionally leak fd, since we never want to close it
    // and we'll never need it again
    return 1;
}

 

struct flock 作为fcntl函数的第三个参数,使用F_SETLK,设置了其参数。

 

更多文章,欢迎访问:http://blog.csdn.net/wallwind

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值