2016-11-20 23:12
浏览 121


flock() is PHP's portable advisory file locking function. They explicitly promote that it even works under windows:

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

I'd like to put an also portable timeout on a blocking flock() (and no busy waiting work around with the LOCK_NB option). In UNIX this can simply be achieved with setting an alarm which would send a SIGALRM:

pcntl_signal(SIGALRM, function() {});
try {
    if (!flock($handle, LOCK_EX)) {
        throw new \Exception("Timeout");
} finally {
    pcntl_signal(SIGALRM, SIG_DFL);

Is there a portable way to put a timeout on a blocking flock()? If so, how?

图片转代码服务由CSDN问答提供 功能建议

flock() 是PHP的便携式咨询文件锁定功能。 他们明确宣传它甚至可以在windows下工作:

flock()允许你执行一个简单的读写器模型,几乎可以在每个平台上使用(包括大多数 Unix衍生产品甚至Windows)。

我想在阻塞 flock()上加上可移植超时 (并且没有忙着等待 LOCK_NB 选项)。 在UNIX中,这可以简单地通过设置警报来实现,该警报将发送 SIGALRM

  pcntl_signal(SIGALRM,function(){}); \  npcntl_alarm(3); 
try {
 if if(!flock($ handle,LOCK_EX)){
 throw new \ Exception(“Timeout”); 
cncntl_alarm(0); \  n pcntl_signal_dispatch(); 

是否有一种可移植的方法可以在阻塞 flock上设置超时 ()? 如果是这样,怎么样?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dousendun8411 2017-01-09 14:52

    I don't think that there is any way to do this on Windows without a busy wait / polling loop.

    PHP implements flock on windows using LockFileEx (see flock_compat.c:132). As you can see from these similar questions, there is no way to set a timeout on LockFileEx or to cancel a process waiting for a LockFileEx request (i.e. there is no equivalent to the SIGALRM signal for this use-case):

    1. LockFile with timeout? (asked 2011)

    Q) If I want to wait for file-lock with timeout, how would I go about it?


    A) write a small loop to check the return code

    1. "LockFileEx can't time out it just hangs" from microsoft.public.win32.programmer.kernel mailing list, 1997

    Q) Does anyone know of a way to get LockFileEx to time out ?


    A) you can only have it fail imemdiately, sleep, and loop back until you reach some retry limit.

    解决 无用
    打赏 举报

相关推荐 更多相似问题