Detailed explanation of the function of locking files using flock in PHP

巴扎黑
Release: 2023-03-14 20:52:02
Original
2037 people have browsed it


flock在官方文档里的解释是:flock() 允许你执行一个简单的可以在任何平台中使用的读取/写入模型(包括大部分的 Unix 派生版和甚至是Windows)。如果锁定会堵塞的话(EWOULDBLOCK 错误码情况下),请将可选的第三个参数设置为 TRUE。锁定操作也可以被 fclose() 释放(代码执行完毕时也会自动调用)。
简单来说,就是对一个文件进行锁定操作,使得多进程访问该文件时受到限制,从而防止冲突。举个例子:
Copy after login
<?php
	$file = fopen("test.txt","w+");
	if (flock($file,LOCK_EX))
	{
	  fwrite($file,"Write something");
	  flock($file,LOCK_UN);
	}
	else
	{
		echo "Error locking file!";
	}

	fclose($file);
?>
Copy after login
说明:
Copy after login
1.这段代码的意思是,以读写方式打开文件test.txt,当一个用户调用该php页面时,即对test.txt文件进行操作,那么就会执行flock($file,LOCK_EX)代码,即将test.txt文件进行独占锁定(该文件只能由该用户进行读写操作),那么如果有其他新的用户想访问该文件,就会被阻塞,直到前者关闭文件(释放锁定)。
Copy after login
2.如果将代码改成flock($file,LOCK_EX+LOCK_NB)表示锁定时直接返回错误,那么如果有新的用户访问该文件,就会输出“Error locking file!”
Copy after login
3.该函数的语法是flock(file,lock,block),其中file必需。规定要锁定或释放的已打开的文件。lock	必需。规定要使用哪种锁定类型。block可选。若设置为 1 或 true,则当进行锁定时阻挡其他进程。
Copy after login
<br/>
Copy after login

For example: Please write a piece of PHP code to ensure that multiple processes write the same file successfully at the same time

function writeData($path, $mode,$data)
{
	$fp = fopen($path, $mode); 
	$retries = 0;
	$max_retries = 100; 
	do{
	   if ($retries > 0) 
	   {
			usleep(rand(1, 10000));
	   }

	   $retries += 1;
	}while (!flock($fp, LOCK_EX) and $retries<= $max_retries); 
 
	if ($retries == $max_retries) 
	{
	   return false;
	}

	fwrite($fp, "$data\n");
	flock($fp, LOCK_UN);
	fclose($fp); 

	return true; 
}
Copy after login


The above is the detailed content of Detailed explanation of the function of locking files using flock in PHP. 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