Comprobar si hay un lock de un archivo


En linux muchos procesos utilizan la carpeta /var/locks para bloquear archivos y así evitar que otros procesos modifiquen ficheros cuando estamos en ello. Para estas cosas podemos utilizar el siguiente codigo:

  1.         /**
  2.          * @name lockfile
  3.          * @desc This function allows to lock or unlock a file with $filename lock file
  4.          * @param string $fileName file and dir where the lockfile will be inserted
  5.          * @param boolean $lock true, create lockfile, false, delete lockfile
  6.          */
  7.         private static function lockfile($fileName, $lock){
  8.                 if($lock){
  9.                         $k = 0;
  10.                         if( file_exists($fileName) ){
  11.                                 while( file_exists($fileName) ){
  12.                                         sleep(1);
  13.                                         Yii::log(“[QM] Someone is locking the file. Waiting 1 sec”,‘info’);
  14.                                         $k++;
  15.                                         If($k >= 30){
  16.                                                 Yii::log(‘[QM] The file is locked for more than ‘.$k.‘ secs. Exiting’,‘info’);
  17.                                                 echo ‘<script>alert(“Contact with your provider because a systemlock has succeded. Code Error: QMLockError”)</script>’;
  18.                                                 //echo Yii::t(‘zii’,’qm.filelocked.timelimit’);
  19.                                                 return 1;
  20.                                         }
  21.                                 }
  22.                         }else{
  23.                                 //nothing to do
  24.                         }
  25.                         file_put_contents($fileName, getmypid());
  26.                 }else{
  27.                         Yii::log(“[QM] Trying to delete “.$fileName.” lock file”,‘info’);
  28.                         unlink($fileName);
  29.                         Yii::log(“[QM] “.$fileName.” lock file deleted”,‘info’);
  30.                 }
  31.                 return 0;
  32.         }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.