search
Homephp教程php手册PHP下如何对文件进行加锁

PHP下如何对文件进行加锁

Jun 13, 2016 am 10:11 AM
lockphptmpfileDownLockhowrightdocumentgetconductLock

/*
*lock_thisfile:获得独享锁
*@param $tmpFileStr 用来作为共享锁文件的文件名(可以随便起一个名字)
*@param $locktype 锁类型,缺省为false(非阻塞型,也就是一旦加锁失败则直接返回false),设置为true则会一直等待加锁成功才返回
*@return 假如加锁成功,则返回锁实例(当使用unlock_thisfile方法的时候需要这个参数),加锁失败则返回false.
*/
function lock_thisfile($tmpFileStr,$locktype=false){
if($locktype == false)
$locktype = LOCK_EX|LOCK_NB;
$can_write = 0;
$lockfp = @fopen($tmpFileStr.".lock","w");
if($lockfp){
$can_write = @flock($lockfp,$locktype);
}
if($can_write){
return $lockfp;
}
else{
if($lockfp){
@fclose($lockfp);
@unlink($tmpFileStr.".lock");
}
return false;
}
}

/**
*unlock_thisfile:对先前取得的锁实例进行解锁
*@param $fp lock_thisfile方法的返回值
*@param $tmpFileStr 用来作为共享锁文件的文件名(可以随便起一个名字)
*/
function unlock_thisfile($fp,$tmpFileStr){
@flock($fp,LOCK_UN);
@fclose($fp);
@fclose($fp);
@unlink($tmpFileStr.".lock");
}
?>

// 使用举例
$tmpFileStr = "/tmp/mylock.loc";

// 等待取得操作权限,假如要立即返回则把第二个参数设为false.
$lockhandle = lock_thisfile($tmpFileStr,true);
if($lockhandle){
// 在这里进行所有需要独占的事务处理。
// ... ...
// 事务处理完毕。
unlock_thisfile($lockhandle,$tmpFileStr);
}

?>

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor