I have a script that I want to make sure only one is running, I am doing:
$fp = fopen("lock.txt", "w");
if (flock($fp, LOCK_EX|LOCK_NB)) { // do an exclusive lock
//Processing code
flock($fp, LOCK_UN);
}else{
echo "Could not lock file!";
}
fclose($fp);
The problem is when I start the second script, it just stays there waiting. If I then stop the first script, the second script will then print "Could Not lock this file". Why doesn't the second script just stop immediately and report that message?
If it ran the second script, it would know that the file is locked and should exit. When I watch my processes I can see the second script sat there ... it's just wating.
Thanks.
EDIT: I have just tried a quick and dirty database lock i.e set a running field to -1 and check for it when the script opens. But that doesn't work. I have also tried using sockets as described: here . It seems like the second file won't even run ... Should I even be worried?
$fp = fopen("lock.txt", "w");
$block = 0;
if (flock($fp, LOCK_EX|LOCK_NB, $block)) { // do an exclusive lock
sleep(5);
flock($fp, LOCK_UN);
echo "Could lock file!";
}else{
echo "Could not lock file!";
}
fclose($fp);
works for me. Try adding the 3'rd parameter
Edit:
You may have some session locking problems:
when you call session_start() it will block(put further requests in a waiting state) any other requests to your script until the original script that started the session has finished. To test this, try either accessing with 2 different browsers, or avoid calling session_start() in this script.
Related
I'd like to allow 1 access at a time to a .txt file until the script finishes, so that it shows the message "Busy" when I open the same PHP again.
I have tried this:
<?php
$file = fopen('file.txt', 'w+');
if (flock($file, LOCK_EX)) {sleep(60); flock($file, LOCK_UN);}
else {echo 'Busy';}
fclose($file);
However it never shows the "Busy" message. Every new tab I open is in "sleep" mode. What am I doing wrong?
The documentation for flock is extremely poor.
As stated in the top comment:
If the file has been locked with LOCK_EX in another process, the CALL WILL BLOCK UNTIL ALL OTHER LOCKS have been released.
The result of this is, you will always be blocking on the call to flock. Your else clause would only execute if there is some error that prevents the file lock from being created - not when the file is already locked.
I trying to implmente a simpler version of the code in this answer:
How to detect whether a PHP script is already running?
The problem described here is my EXACT situation. I want to prevent cron from launching the same script if it's already running.
I started with this simple test code:
<?php
$script_name = __FILE__;
$lock_file_name = basename($script_name, ".php") . ".lock";
$fp = fopen($lock_file_name, "c");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
//ftruncate($fp, 0); // truncate file
//fwrite($fp, "Write something here\n");
//fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
echo "GOT LOCK\n";
sleep(20);
} else {
echo "Couldn't get the lock!\n";
}
flock($fp, LOCK_UN); // release the lock
fclose($fp);
?>
As I understand it, I launch this code in one console and read the Got Lock. If I launch it in another console the I should get the Coudn't get the lock message. Howver I get the Got Lock message both times.
What am I doing wrong?
The file is only locked for the duration of the script. Once the PHP finishes its activities the script tereminates and then the OS unlocks the file.
Note that your sleep(20) call is coming after you have unlocked the file, so there is no pause when the file is locked. So it sounds like you're in effect calling the single script twice in sequence rather than in parallel.
Solution:
Move the sleep(20) statement to before the lock is removed (actually you unlock twice so simply removing the first unlock does this).
$fp = fopen($lock_file_name, "c");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
echo "GOT LOCK\n";
/** this time window allows you to run another parallel script to prove the locking mechanism works **/
sleep(20);
} else {
echo "Couldn't get the lock!\n";
}
flock($fp, LOCK_UN); // release the lock
fclose($fp);
I came across this link while trying to learn how to lock files to prevent a script reading from a file as another is writing, or two scripts writing to the same file simultaneously.
I created two scripts, readandwritelock.php and readlock.php, the first script to retrieve the file with file_get_contents, append it and then write back to the same file with file_put_contents($file, $data, LOCK_EX), and the second that just retrieves the file with file_get_contents after flock($file, LOCK_SH).
<?php
//readandwritelock.php
$myfile = fopen('15-11-2018.txt', 'r+');
if (flock($myfile, LOCK_SH)) {
echo "Gotten lock<br>";
$current = file_get_contents('15-11-2018.txt');
/*I commented this on my second test to see if file_put_contents will work.
After uncommenting and third test, it does not work anymore.
if (flock($myfile, LOCK_UN)) {
echo "Unlocked<br>";
}*/
$current .= "appending";
if (file_put_contents('15-11-2018.txt', $current, LOCK_EX)) {
echo "Success";
}
else {
echo "Failed";
//browser loads indefinitely so this does not run
}
fclose($myfile);
}
?>
The problem I am facing is that the first try I was able to file_get_contents after getting the lock, and then releasing the lock and proceed to append and file_put_contents($file, $data, LOCK_EX). However on the second try I decided to comment the releasing of the LOCK_SH lock to test and see what would happen. The script file loads indefinitely (Waiting for localhost...) on my browser, so I reverted back the changes for my third try, but this time the script file still loads indefinitely. It's as if the LOCK_SH was never released.
I must be doing something wrong, but I do not know what exactly it is. Could someone explain?
This was tested on XAMPP and macOS High Sierra and Chrome.
<?php
//readlock.php
//works as normal
$myfile = fopen('15-11-2018.txt', 'r');
if (flock($myfile, LOCK_SH)) {
echo "Gotten lock<br>";
$current = file_get_contents('15-11-2018.txt');
echo $current;
if (flock($myfile, LOCK_UN)) {
echo "<br>Unlocked";
}
fclose($myfile);
}
?>
The reason why your browser seems to load indefinitely is because your PHP file never finishes.
First you get a LOCK_SH (a shared or read lock) for your file, which is fine while you are reading the content.
The problem is that you also try to get a LOCK_EX (an exclusive lock) on the same file in the file_put_contents function. Therefore the file_put_contents functions blocks until all other locks (shared AND exclusive ones) are unlocked, which can't work (this is a deadlock).
For your code to work properly, you can either try to get an exlusive lock in the first place
if( flock($myfile, LOCK_EX) ) {
// ...
or you unlock the shared lock before you write
flock($myfile, LOCK_UN);
if ( file_put_contents('15-11-2018.txt', $current, LOCK_EX) ) {
// ...
In general it is a good idea to keep a locks life as short as possible. If you plan to make extensive manipulations to your data between reading and writing, I would recommend to unlock the file right after reading and lock it again right for writing.
I hvave a cron job that is doing some updates. After completion of that process i need to run another cron job for inserting that updated records into another table.For this I am trying this script.
$output = shell_exec('ps -C php -f');
if (strpos($output, "php do_update.php")===false) {
shell_exec('php insert_process.php');
}
But it is not doing any thing and i am getting ps is not internal / external command.
So how can I find that first cron job execution is completed or not?Once that is executed then i will run the second cron for inserting data. Any holp would be greatly appreciated.
You could use some kind of a lock file.
First file:
at the beginning of the first script create empty file on the disk called lockfile.txt (or any other name)
at the end remove the file from the disk
Second file
check if the file called lockfile.txt exists, if not - run the code
you can use flock on running the do_update.php add a lock to it and in
`insert_process.php` run the process if your previous lock is released
in your do_update.php add this
$fp = fopen("lock.txt", "r+");
if (flock($fp, LOCK_EX)) {
//do your process
flock($fp, LOCK_UN); //release the lock
}
in your insert_process.php add this
$fp = fopen("lock.txt", "r+");
if (flock($fp, LOCK_EX | LOCK_NB)) { // checks for the lock
// do your process
}
I have a cache file that is updated every hour or so. The file size ranges from 100KB to 1MB. The way the cache is updated is with the file_put_contents() method.
Only the server writes to the file. However, there is continuous access to the file. The file is accessed by users by a script that performs a one time read through readfile() to echo it to the user.
If the file is being read by the caching script, and the server runs the user reading script, or the other way around, would there be a problem? Or is this handled automatically by PHP>
Basically, you should lock the file while writing or reading. At least, it guarantees that there is no problem. It is the way of good programming!. The example is shown below.
<?php
$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
fwrite($fp, "Write something here\n");
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
?>
More information