编程 close 一个只读 fd,进程里所有 fcntl 记录锁全失效:l_pid 判据与 3.15 才有 OFD 锁的边界

2026-12-04 00:05:47

close 一个无关的 fd,整个进程的 fcntl 锁就没了

POSIX 记录锁(fcntl 的 F_SETLK / F_SETLKW / F_GETLK)归属的是 [i-node, pid] 这个二元组,不是某个文件描述符。结论很直接:只要本进程关闭了指向该文件的任意一个 fd,哪怕那个 fd 是另外一次 open() 拿到的、上面的锁也完全没动过,该进程在这个文件上的全部记录锁都会立即消失。这是 POSIX 规定的行为,不是内核 bug,也不是能靠重试绕过去的竞态。

同一进程换第二个描述符去抢锁不会自冲突(返回 0,锁并入进程名下);fork 出的子进程不继承锁,但用继承的 fd 解锁是空操作;真正能做到「谁持有谁负责」的是 3.15 起引入的 OFD 锁。

参考文档:

实测环境:Linux 3.10.0-1160.el7.x86_64、gcc 4.8.5、glibc 2.17(CentOS 7)。

三层结构决定锁挂在哪

文件描述符(进程内表项)→ file object(打开文件描述,含偏移量等状态)→ i-node。同一进程多次 open() 得到的是不同 file object,指向同一 i-node;dup() / fork() 复制的是指向同一 file object 的引用。

记录锁挂在 [i-node, pid] 上,所以它和 fd 没有绑定关系,任何一次 close() 都会作为「进程关闭了该文件」的信号,把这一对上的所有锁清掉。OFD 锁挂在 open file description 上,才会随最后一份引用的关闭才释放。

实测一:close 无关 fd 后锁静默失效

父进程在 fd1 上加 F_SETLK 写锁(l_len=0,到 EOF),fork 子进程自己 open() 同一路径抢锁;父进程保持 fd1 打开、从未 F_UNLCK,只额外 open() 一个只读 fd2 然后 close(fd2)。

=== POSIX 记录锁 ===
parent: 在 fd1=4 上 posix = 0
阶段1 持锁时,别人来抢:
child(pid=13042): lock = -1 errno=11(Resource temporarily unavailable)
parent: open 了 fd2=5 又 close,fd1 仍开着,从未 UNLCK
阶段2 close 无关 fd 之后,别人来抢:
child(pid=13043): lock = 0   All process-owned locks associated with a file for a given process shall be removed when any file descriptor for that file is closed by that process (even if via a different open file description) or the process holding that file descriptor terminates. Process-owned locks shall not be inherited by a child process.
>
> All OFD-owned locks ... removed when all file descriptors associated with that open file description have been closed.

`man 2 fcntl_locking` 的对应描述:record locks aren't inherited by child created by `fork`, but preserved across `execve`;传统记录锁 associated with process,OFD 锁 associated with open file description,inherited across `fork`,only released on last close。

`lockf()` 在 Linux 上是 `fcntl` 记录锁的封装(只支持排他锁),所以同样具备「close 任意 fd 全释放」的问题,换成 `lockf()` 并不能规避。

互斥边界:

- Linux 2.0 起 `flock()` 是独立系统调用,与 `fcntl` 锁互不影响,各走两套锁表;在 BSD 系两者会互相影响。
- NFS 上这条边界不成立:2.6.12 起客户端把 `flock()` 模拟成整文件区间锁,因此 NFS 上 `flock` 与 `fcntl` 锁会互相排斥。
- NFSv4 leasetime 默认 90 秒(`/proc/fs/nfsd/nfsv4leasetime`);Linux 3.12 起丢失锁之后对该文件的 I/O 会报 `EIO`,直到进程 close 并重新 open;`nfs.recover_lost_locks` 默认 0。
- 强制锁(mandatory)已废弃且不可靠,不在此讨论。

## 排查手段

`lslocks` 与 `/proc/locks` 的 TYPE 列直接标出锁的类型:`POSIX`、`FLOCK`、`OFDLCK`(OFD 锁的 pid 列为 -1)。看到 pid 是具体进程号,说明对手是进程锁;看到 -1,说明对手是描述符锁。用 `F_GETLK` 查询时,返回结构里的 `l_pid` 同样能区分这两种情况——排查「锁莫名消失」时,先确认是不是同进程别处的 `open`/`close` 把锁清掉了。

## 修复方案

1. 换成 `F_OFD_SETLK` 系列(需要内核 3.15+ 与对应头文件),锁随描述符生命周期走,`close` 无关 fd 不再有影响。
2. 整个进程对该文件只 `open()` 一次,全程持有这一个 fd,禁止其他代码路径再 `open` 同一文件(包括只读的日志、配置校验路径)。
3. 应用层维护进程内全局锁表(引用计数 + rwlock)包住 `fcntl`,由锁表决定何时真正 `F_UNLCK`,避免裸调用散落在各处。
4. 改用 `flock`,或让锁文件与数据文件路径分离,使读写数据文件的 fd 不会撞上锁主体的 `[i-node, pid]`。

## 可复现的最小片段

```c
#define _GNU_SOURCE
#include
#include
#include
#include
#include
#include

static void fill(struct flock *fl, short type)
{
memset(fl, 0, sizeof *fl);
fl->l_type   = type;
fl->l_whence = SEEK_SET;
fl->l_start  = 0;
fl->l_len    = 0;          /* 0 = 到 EOF */
}

static int try_lock(int fd, short type)
{
struct flock fl;
fill(&fl, type);
#ifdef F_OFD_SETLK
int r = fcntl(fd, F_OFD_SETLK, &fl);
#else
int r = fcntl(fd, F_SETLK, &fl);
#endif
printf("lock type=%d ret=%d %s\n", type, r, r ? strerror(errno) : "");
return r;
}

static void who(int fd)
{
struct flock fl;
fill(&fl, F_WRLCK);
if (fcntl(fd, F_GETLK, &fl) == -1) {
perror("F_GETLK");
return;
}
if (fl.l_type == F_UNLCK)
printf("no conflicting lock\n");
else
printf("blocked by pid=%d type=%d start=%lld len=%lld\n",
(int)fl.l_pid, (int)fl.l_type,
(long long)fl.l_start, (long long)fl.l_len);
}

static void child_try(const char *path)
{
pid_t p = fork();
if (p == 0) {
int c = open(path, O_RDWR);
if (c  1 ? argv[1] : "/tmp/lockdemo";
int fd1 = open(path, O_RDWR | O_CREAT, 0644);
if (fd1 < 0) { perror("open"); return 1; }

try_lock(fd1, F_WRLCK);     /* 阶段 1:持锁 */
child_try(path);            /* 应失败 */

int fd2 = open(path, O_RDONLY);
close(fd2);                 /* 关掉一个无关 fd,fd1 仍开着 */
child_try(path);            /* POSIX: 成功;OFD: 仍失败 */

close(fd1);
return 0;
}
复制全文 生成海报 锁与并发 文件锁 fcntl flock Linux C

推荐文章

程序员茄子在线接单