Question

I'm using flock() function to check if another instance of the script is already running by obtaining the lock on a temporary file so next instance should check if the file is not locked otherwise it stops

<?php    
$fp = fopen("/var/tmp/your.lock", "w");
if (!flock($fp, LOCK_EX|LOCK_NB)) { // try to get exclusive lock, non-blocking
    die("Another instance is running");
} 

//my script 
sleep(10);
echo 'completed successfully';

the script works without problem when calling the file twice at the same time from different browsers while it waits if I opened two instances at the same time from the same browser i.e the first call get the lock and the second wait for the lock and not closing

I know there may be other ways to check if a file an instance is already working but most of them will do a thing then undo it and in my use case the script may end any time as it may take long time or exceed memory limit or by any reason

any help ?

Was it helpful?

Solution

The problem was :

calling the same script twice with the same url from the browser will thread via the same process and flock() function non-blocking working on the process layer causing the second script to wait

as example calling example.com/test.php twice will cause the two requests work on the same process wile appending any random variable will create separate process for each single request like

example.com/test.php?rand=1
example.com/test.php?rand=2

works great .

OTHER TIPS

Run the same script from the command line twice. I would be willing to bet it works just fine.

Chances are that your browser is rate limiting connections to the server by only allowing one connection at a time to any given host. The fact that you get different results in different browsers would indicate that it's not a PHP problem, as PHP will perform the same regardless of the browser requesting the page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top