? Php /************************************** * ******** filelock * @ authorZealLi * Handle
/*************************************** *******
* File lock
* @ Author Zeal Li
* Http://www.zeali.net/
**************************************** *******/
/*
* Lock_thisfile: obtains the exclusive lock.
* @ Param $ tmpFileStr is used as the file name of the shared lock file (you can create a name as needed)
* @ Param $ locktype: lock type. the default value is false (non-blocking type, that is, if the lock fails, false is directly returned). if it is set to true, the system will wait until the lock is successful before returning.
* @ Return if the lock is successful, the lock instance is returned (this parameter is required when the unlock_thisfile method is applied). If the lock fails, false is returned.
*/
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: Unlock the previously obtained lock instance
* @ Param $ fp lock_thisfile return value
* @ Param $ tmpFileStr is used as the file name of the shared lock file (you can create a name as needed)
*/
Function unlock_thisfile ($ fp, $ tmpFileStr ){
@ Flock ($ fp, LOCK_UN );
@ Fclose ($ fp );
@ Fclose ($ fp );
@ Unlink ($ tmpFileStr. '. lock ');
}
?>
// Application example
$ TmpFileStr = '/tmp/mylock. loc ';
// Wait for the master permission to be obtained. if you want to return immediately, set the second parameter to false.
$ Lockhandle = lock_thisfile ($ tmpFileStr, true );
If ($ lockhandle ){
// Perform all the transactions that require exclusive processing.
//......
// The transaction has been processed.
Unlock_thisfile ($ lockhandle, $ tmpFileStr );
}
?>