How to find PID in php

I am writing a php script that will go through cron. Its task is to call other php scripts. Called scripts can also be executed externally. I want that although one file is being executed, it should not be running at the same time. To make everything clear, consider the following

Suppose there is one script master.php that calls two other scripts, script1.php and script2.php, one after the other. Now, as soon as it is called script1.php, it starts execution and takes 10 minutes to complete the processing. This Script1.php can also be started by the user separately during these 10 minutes.

What I want to do while this script is in the middle of its processing, it should not be executed only in parallel.

Is there any way to achieve this? (Perhaps by checking the PID of the script 1.php).

Thanx in advance.

+3
source share
5 answers

This is how I do it with a pid file. Also, if the script runs 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 detach the pid file at the end of the script:

unlink($pid_file);

If you want to run the script at the completion of the first instance, replace exit () with sleep (1) and put the entire block in a loop.

+4
source

When the script starts, check if the lock file exists. If not, create it. The next time the script is launched while another session is running, it will end because the lock file exists. At the end of the script, delete the lock file.

+3
source

pid 1 , , script. pid php getmypid();

0

"Script1.txt" script script.

script ( Script1.php) . , , script .

0
source

I believe exec waits until execution is complete. So master.php will look something like this:

exec ("/ path / to / PHP script1.php");
exec ("/ path / to / PHP script2.php");

-1
source

All Articles