Reputation: 229
I am writing a php script which will run through cron . Its task is to call other php scripts. The called scripts can also be executed externally. What I want is that while one file is executing, it should not be executed concurrently. To make things clear, consider following
Suppose there is one script master.php which calls to two other scripts script1.php and script2.php one after another. Now, once it called script1.php, it starts executing and take 10 mins to finish its processing. This Script1.php can also be run by user separately in these 10 mins.
What I want to do is while this script is amid its processing, it should not execute only parallely.
Is there a way to achieve this ? (Perhaps by checking the PID of script1.php).
Thanx in advance.
Upvotes: 3
Views: 2110
Reputation: 2029
This is how I do it with a pid file. Also if the script is running for more than 300 seconds, it will be killed:
$pid_file = '/var/run/script1.pid';
if (file_exists($pid_file)) {
$pid = file_get_contents($pid_file);
if ($pid && file_exists('/proc/' . $pid)) {
$time = filemtime($pid_file);
if (time() - $time > 300) {
posix_kill($pid, 9);
} else {
exit("Another instance of {$argv[0]} is running.\n");
}
}
}
$pid = posix_getpid();
if (!file_put_contents($pid_file, $pid)) exit("Can't write pid file $pid_file.\n");
And then unlink the pid file at the end of the script:
unlink($pid_file);
If you want to run the script when the first instance finish - replace the exit() with sleep(1) and put the whole block in a loop.
Upvotes: 4
Reputation: 845
I believe exec waits until execution has completed. So master.php would then be something like:
exec("/path/to/php script1.php");
exec("/path/to/php script2.php");
Upvotes: -1
Reputation: 6286
Just make a textfile called "Script1.txt" once you start the script, and delete the file at the end of the script.
Before the actual script runs (in the first lines of Script1.php for instance) check for the existence of that file. If it exists you know your script is already running.
Upvotes: 0
Reputation: 6159
you can store the pid of script1 in a temporary file, pipe, shared memory, or directly at the parent script. You can get the pid from a php process with getmypid();
Upvotes: 0
Reputation: 4875
When the script starts, check if a lock file exists. If not, create one. The next time the script is started while another session of it is running, it will exit, because the lock file exists. At the end of the script, remove the lock file.
Upvotes: 3