Home  >  Article  >  Backend Development  >  Detailed explanation of the function of locking files using flock in PHP

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

巴扎黑
巴扎黑Original
2017-08-10 15:33:302036browse


flock在官方文档里的解释是:flock() 允许你执行一个简单的可以在任何平台中使用的读取/写入模型(包括大部分的 Unix 派生版和甚至是Windows)。如果锁定会堵塞的话(EWOULDBLOCK 错误码情况下),请将可选的第三个参数设置为 TRUE。锁定操作也可以被 fclose() 释放(代码执行完毕时也会自动调用)。
简单来说,就是对一个文件进行锁定操作,使得多进程访问该文件时受到限制,从而防止冲突。举个例子:
<?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);
?>
说明:
1.这段代码的意思是,以读写方式打开文件test.txt,当一个用户调用该php页面时,即对test.txt文件进行操作,那么就会执行flock($file,LOCK_EX)代码,即将test.txt文件进行独占锁定(该文件只能由该用户进行读写操作),那么如果有其他新的用户想访问该文件,就会被阻塞,直到前者关闭文件(释放锁定)。
2.如果将代码改成flock($file,LOCK_EX+LOCK_NB)表示锁定时直接返回错误,那么如果有新的用户访问该文件,就会输出“Error locking file!”
3.该函数的语法是flock(file,lock,block),其中file必需。规定要锁定或释放的已打开的文件。lock	必需。规定要使用哪种锁定类型。block可选。若设置为 1 或 true,则当进行锁定时阻挡其他进程。
<br/>

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; 
}


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!

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