inactive Posted April 11, 2008 Share Posted April 11, 2008 Does anyone know how i can use flock to generate an error if it is unable to gain an exclusive lock, rather than just wait for any current locks to be unlocked? Basically when i run my script i want a file to be locked, so that if the same script is run at the same time, it will generate an error strait away, and not just wait for the first one to finish (and unlock). I refer to something i read at http://www.hudzilla.org/phpbook/read.php/8_11_0: Sometimes it is not desirable to have your scripts wait for a file to become unlocked, and in this situation you can add an extra option to the second parameter using the bitwise OR operator, |. If you pass in LOCK_NB ORed with your normal second parameter, PHP will not block when it requests a file lock. This means that if the file lock is not available, flock() will return immediately with false rather than hang around waiting for a lock to become available. Here is how that looks in code: <?php $fp = fopen("foo.txt", "w"); if (flock($fp, LOCK_EX | LOCK_NB)) { echo "Got lock!\n"; sleep(10); flock($fp, LOCK_UN); } else { print "Could not get lock!\n"; } ?> This time, the first script will get the lock and print "Got lock!", whereas the second will fail to get the lock, return immediately, and print "Could not get lock!" I have tried this, but it does not work for me. Running XP SP2 w/ Apache 2.2.8 & PHP 5.2.5 Link to comment https://forums.phpfreaks.com/topic/100572-solved-problems-with-flock/ Share on other sites More sharing options...
inactive Posted April 11, 2008 Author Share Posted April 11, 2008 Wow I thought this might have a relatively easy one. Maybe time to try something else... Link to comment https://forums.phpfreaks.com/topic/100572-solved-problems-with-flock/#findComment-514401 Share on other sites More sharing options...
inactive Posted April 11, 2008 Author Share Posted April 11, 2008 Well after a bit of research, It appears this does work, and the problem may have been with how the browser was handling the requests in each session. If I used two different tabs in the same browser, they would both show 'Got Lock', while if I used two different browsers, the second request would show the error. I think when in the same browser, the second response may be like a cached response. This is not really my are of expertise however, so I may be wrong. Link to comment https://forums.phpfreaks.com/topic/100572-solved-problems-with-flock/#findComment-514411 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.