简体   繁体   English

如何锁定文件以防止读取/写入同一文件的多个ajax请求?

[英]How can I lock a file to protect against multiple ajax requests reading/writing the same file?

I am currently trying to prevent a file from being read if it already exists and has content in it. 我目前正在尝试阻止文件被读取,如果它已经存在并且其中包含内容。 I am using the flock method to try and prevent other instances of the script running from accessing it, but it is not working. 我正在使用flock方法尝试阻止脚本运行的其他实例访问它,但它无法正常工作。 This is only an issue with servers with multiple cores. 这只是具有多个核心的服务器的问题。

while ($aEvent = current($aEvents)){
    $sLockFile = '/var/tmp/'.md5($aEvent['id']).'.LCK';
    $oFile = fopen($sLockFile, 'c+');
    if (flock($oFile, LOCK_EX) && fgets($oFile) == '') {
        fwrite($oFile, 'locked');
        fclose($oFile);
    } else {
        fclose($oFile);
        next($aEvents);
        continue;
    }
    /*
     * Do stuff here.
     */
    next($aEvents);
}

So from this code, I expect that a file is created, locked, and written to, and any request that tries to subsequently read/write the file is either stopped at the flock call or the empty check. 因此,从这段代码中,我希望创建,锁定和写入文件,并且任何尝试随后读取/写入文件的请求都会在flock调用或空检查时停止。 When in reality it seems like if the code is hit with enough ajax requests at the same time, the same file is being created/overwritten multiple times. 实际上,如果代码同时被足够的ajax请求命中,则会多次创建/覆盖相同的文件。 Is there any way to keep PHP thread safe? 有没有办法保持PHP线程的安全?

It sounds like you want to add the LOCK_NB bit to your flock call. 听起来您想要将LOCK_NB位添加到您的flock调用中。 From the flock docs : 来自flock docs

By default, this function will block until the requested lock is acquired; 默认情况下,此功能将阻止,直到获取所请求的锁定为止; this may be controlled with the LOCK_NB option 这可以通过LOCK_NB选项来控制

Your code will block on each call to flock until a lock can be acquired. 您的代码将在每次调用flock时阻止,直到可以获取锁定。 It sounds like you want to skip to the else block if a lock exists. 如果存在锁,听起来你想跳到else块。 If so, you want to do this in your code: 如果是这样,您希望在代码中执行此操作:

<?php
if (flock($oFile, LOCK_EX | LOCK_NB) && fgets($oFile) == '')
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM