Linux flock(fd,LOCK_EX | LOCK_NB)会错误地失败吗? [英] Can Linux flock(fd, LOCK_EX|LOCK_NB) fail spuriously?

查看:109
本文介绍了Linux flock(fd,LOCK_EX | LOCK_NB)会错误地失败吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样一种情况:两个进程同时尝试使用 flock(fd, LOCK_EX|LOCK_NB) 对某个文件设置排他锁.

Consider a situation where two processes make concurrent attempts at placing an exclusive lock on some file using flock(fd, LOCK_EX|LOCK_NB).

如所示,尝试是 non-blocking ,因此这两个进程之一应该会因 EWOULDBLOCK 而失败.

As indicated, the attempts are non-blocking, so one of the two processes is supposed to fail with EWOULDBLOCK.

这是我的问题: flock()的(Linux)实现是否可以确保在每种情况下,两个过程之一都能成功?或者,即使没有其他人在干扰,两者是否都可能都以 EWOULDBLOCK 失败?

Here is my question: Does the (Linux) implementation of flock() guarantee that exactly one of the two processes will succeed in every such case? Or, is it possible that both end up failing with EWOULDBLOCK even when nobody else are interfering?

简而言之,flock(fd, LOCK_EX|LOCK_NB) 是否可以使用 EWOULDBLOCK 虚假失败?

In short, can flock(fd, LOCK_EX|LOCK_NB) ever fail spuriously with EWOULDBLOCK?

我主要对Linux提供的 flock()的版本感兴趣,但是,在其他系统(例如OS X)上有关 flock()的信息是最受欢迎的

I am mainly interested in the version of flock() offered by Linux, but information about flock() on other systems, such as OS X, is most welcome.

此外,我认为答案是相同的,而不管锁是排他锁( LOCK_EX )还是共享锁( LOCK_SH ).如果没有,让我知道.

Also, I assume that the answer is the same regardless of whether the locks are exclusive (LOCK_EX) or shared (LOCK_SH). If not, let me know.

推荐答案

阅读人羊群(2):

EWOULDBLOCK文件已锁定,并且已选择LOCK_NB标志.

EWOULDBLOCK The file is locked and the LOCK_NB flag was selected.

因此,获取EWOULDBLOCK表示文件已被锁定.如果可以确保只有两个进程参与其中,则它们永远不会在同一文件上同时获得EWOULDBLOCK.

So getting EWOULDBLOCK means the file is already locked. If it is guaranteed that your two processes are the only ones involved, they will never get EWOULDBLOCK on the same file at the same time.

请注意,主题是另一回事.线程通常共享文件描述符,因此同一进程中的多个线程可以在同一文件上成功调用flock().

Please note that threads is a different story. Threads normally share file descriptors, so several threads within the same process can call flock() successfully on the same file.

这篇关于Linux flock(fd,LOCK_EX | LOCK_NB)会错误地失败吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆