dongyang4615 2013-03-01 01:24
浏览 68
已采纳

PHP flock函数限制和txt缓存文件

I have a fairly basic PHP script that caches data to a text file. I need to come up with a solution that prevents two running instances of the script from writing to the file at the same time. I've looked into the PHP flock function, however, the PHP manual (http://php.net/manual/en/function.flock.php) mentioned one big limitation:

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

I've got two questions regarding this warning that I'm hoping someone can answer. First, how can I check if my implementation of flock is done at the process level or not? Btw, I'm running CentOS, with cPanel.

Second, if my implementation is at the process level, does that mean that one running instance of my script will not be aware of a lock done by another running instance of the same script? Or do script instances run on separate threads and not separate processes? Any clarification about this is very much appreciated.

Thanks.

  • 写回答

1条回答 默认 最新

  • dongqing7789 2013-03-01 01:33
    关注

    The only common case would be running Apache, with the some kind threaded (non-forking) npm. 99% of the cases you are not running PHP threaded.. it's a relatively safe assumption.

    Aside from that, it may be worth trying to avoid locking..

    The biggest issue you have is that 2 processes may be writing at the same time, or 1 process reads the cache when it's not fully generated. The easiest way to get around this, is to let the PHP script generate the cache in a different file in a temporary location. When the file is written, just move it into place (with rename()). File moves are guaranteed to be atomic when it's happening on the same mount.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度