Share two solutions for PHP to implement multiple processes writing the same file at the same time

黄舟
Release: 2023-03-07 07:50:01
Original
3299 people have browsed it

Test point: Understanding of function

fopen: Open a file or URL

参数1:文件地址或者URL  
参数2:mode 参数指定了所要求到该流的访问类型  
    'r' 只读方式打开,将文件指针指向文件头。  
    'r+'    读写方式打开,将文件指针指向文件头。  
    'w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。  
    'w+'    读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。  
    'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。  
    'a+'    读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
Copy after login

fwrite: Write a file

参数1:文件名文件系统指针  
参数2: 要写入的内容 string类型  
返回值: 写入成功返回写入的字符数,失败返回false
Copy after login

flock: Lightweight advisory file locking

参数1:文件系统指针,是典型地由 fopen() 创建的 resource(资源)。  
参数2:模式  
    LOCK_SH取得共享锁定(读取的程序)。  
    LOCK_EX 取得独占锁定(写入的程序。  
    LOCK_UN 释放锁定(无论共享或独占)。  
    如果不希望 flock() 在锁定时堵塞,则是 LOCK_NB(Windows 上还不支持)。  
  
返回值:成功时返回 TRUE, 或者在失败时返回 FALSE。
Copy after login

fclose: Close an open file pointer

参数1:文件名  
参数2:成功时返回 TRUE, 或者在失败时返回 FALSE。
Copy after login

Option 1

function writeData($filepath, $data)   
{   
    $fp = fopen($filepath,'a');    
    do{   
        usleep(100);   
    }while (!flock($fp, LOCK_EX));  //LOCK_EX 取得独占锁定(写入的程序)进行排它型锁定 获取锁 有锁就写入,没锁就得  
    $res = fwrite($fp, $data."\n");   
    flock($fp, LOCK_UN);    //LOCK_UN 释放锁定(无论共享或独占)。  
    fclose($fp);    
    return $res;   
}
Copy after login

Option 2 (Method of marking yourself)

function write_file($filename, $content)  
{  
    $lock = $filename . '.lck';  
    $write_length = 0;  
    while(true) {  
        if( file_exists($lock) ) {  
            usleep(100);  
        } else {  
            touch($lock);  
            $write_length = file_put_contents($filename, $content, FILE_APPEND);  
            break;  
        }  
    }  
    if( file_exists($lock) ) {  
        unlink($lock);  
    }  
    return $write_length;  
}
Copy after login

The above is the detailed content of Share two solutions for PHP to implement multiple processes writing the same file at the same time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!