Home  >  Article  >  Backend Development  >  PHP enables multiple processes to write to a file at the same time

PHP enables multiple processes to write to a file at the same time

不言
不言Original
2018-04-26 16:04:461919browse

This article mainly introduces the realization of multiple processes writing a file at the same time in PHP. It has a certain reference value. Now I share it with you. Friends in need can refer to it

<?php
function writefile( $filename, $data ){
 $fp = fopen( $filepath, &#39;a&#39;);    / /以追加的方式打开文件,返回的是指针
 do{
  usleep(100 ); //暂停执行程序,参数是以微秒为单位的
 }while( !flock( $fp, LOCK_EX ) );//以独享写入的方式锁定文件,成功则返回TRUE,否则FALSE
}
 $res = fwrite( $fp, $data."/n");// 以追加的方式写入数据到打开的文件
 flock( $fp, LOCK_UN );//解锁,以让别的进程进行锁定
 fcloce( $fp );//关闭打开的文件指针
 return $res;//返回写入结果
?>

Related recommendations:

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

The above is the detailed content of PHP enables multiple processes to write to a file at the same time. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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