简体   繁体   English

多个进程读取同一文件的PHP

[英]Multiple process read same file php

I have a little problem inside my application. 我的应用程序内部有一个小问题。 I have many process launched automatically, from the server with crontab, written in php to read file inside a folder. 我使用crontab从服务器自动启动了许多进程,这些进程是用php编写的,以读取文件夹中的文件。

Sometimes different process read the same file and create a problem inside the application. 有时,不同的进程会读取同一文件,并在应用程序内部造成问题。 Is there a way to manage this problem? 有没有办法解决这个问题? Actually I read all files inside a folder, read each of them and delete immediately, but sometimes another process read the same file before I delete It. 实际上,我读取了文件夹中的所有文件,读取了每个文件并立即将其删除,但是有时另一个进程在删除文件之前会读取相同的文件。

This is my script written with cakephp3 (so some classes like File is only for cakephp3 but isn't the point of the question) to read and delete: 这是我用cakephp3编写的脚本(因此,诸如File之类的某些类仅适用于cakephp3,但并不是问题的重点)以读取和删除:

$xml_files = glob(TMP . 'xml/*.xml');
foreach($xml_files as $fileXml)
{
   //read the file and put into a string or array or object
    $explStr = explode('/', $fileXml);
    $filename = $explStr[count($explStr) - 1];
    $path = TMP . '/xml/' . $filename;
    $file = new File($path, false);

    if($file->exists()){
        $string = $file->read();

        $file->close();
        $file->delete();
    }
}   

使用flock()获取(或尝试获取)文件锁并采取相应的措施。

It's called a race condition, and when working with files you could lock the file when process A uses it, it locks it, then other processes would check if it's locked and if it is then do nothing. 这被称为竞争条件,当使用文件时,您可以在进程A使用文件时将其锁定,然后将其锁定,然后其他进程会检查文件是否被锁定,然后什么也不做。 Then unlock the file when process A has finished with it. 然后在进程A完成文件后将其解锁。

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

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