dsxfa26482 2016-11-20 23:12
浏览 129
已采纳

是否有一种可移植的方法来为flock()设置超时?

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() {});
pcntl_alarm(3);
try {
    if (!flock($handle, LOCK_EX)) {
        throw new \Exception("Timeout");
    }
} finally {
    pcntl_alarm(0);
    pcntl_signal_dispatch();
    pcntl_signal(SIGALRM, SIG_DFL);
}

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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站