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.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c