note 74829 modified in function.flock by danbrown

From: Date: Mon, 18 May 2009 00:35:52 +0000
Subject: note 74829 modified in function.flock by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155392@lists.php.net to get a copy of this message
Hello, I want to give an example how to lock file with two or more flags (for example reading and writing). IMPORTANT: each locking should be done separately, the correct way of using flock() is: <?php flock($fp, LOCK_EX); flock($fp, LOCK_SH); ?> and NOT like these: <?php flock($fp, LOCK_EX and LOCK_SH); flock($fp, LOCK_EX or LOCK_SH); flock($fp, LOCK_EX + LOCK_SH); ?> Furthermore if someone has not pay attention to function’s description - flock does not lock any file in the right way. The file is still accessible for reading/writing, in other words these functions: file(), file_get_contents() and even fopen($file, ‘r’) will ignore the lock. I think PHP mechanism works something like this: as soon as file lock was successful, the function flock() writes somewhere (in its own “DB” for example) that file handle is locked with some flag and nothing more. It is up to the developer to check if file is locked or not before doing any operations. Hope this post makes clear the flock() function’s working principles. Regards Vitali Simsive == During test I have discovered that if you have locked file for writing (LOCK_EX) both read and write will not be accessible from other scripts. In case of read locking (LOCK_SH) only writing will not be accessible for other PHP scripts but they will be able to read file simultaneously. --was-- Hello, I want to give an example how to lock file with two or more flags (for example reading and writing). IMPORTANT: each locking should be done separately, the correct way of using flock() is: <?php flock($fp, LOCK_EX); flock($fp, LOCK_SH); ?> and NOT like these: <?php flock($fp, LOCK_EX and LOCK_SH); flock($fp, LOCK_EX or LOCK_SH); flock($fp, LOCK_EX + LOCK_SH); ?> Furthermore if someone has not pay attention to function’s description - flock does not lock any file in the right way. The file is still accessible for reading/writing, in other words these functions: file(), file_get_contents() and even fopen($file, ‘r’) will ignore the lock. I think PHP mechanism works something like this: as soon as file lock was successful, the function flock() writes somewhere (in its own “DB” for example) that file handle is locked with some flag and nothing more. It is up to the developer to check if file is locked or not before doing any operations. Hope this post makes clear the flock() function’s working principles. Regards Vitali Simsive http://php.net/manual/en/function.flock.php

« previous php.notes (#155392) next »