Call us Toll-Free:
1-800-218-1525
Live ChatEmail us

 Sponsors

PHP Check if script is running

Mike Peters, 05-19-2007
The code below is helpful to check if an existing PHP script is already running.

It takes advantadge of PHP's built-in flock function that allows us to establish an exclusive lock, that gets automatically released by the operating system once the script that established the lock terminates.

In your main worker script, place this code at the top of the file:

// Open PID file
$tmpfilename = "/var/run/myscript.pid";
if (!($tmpfile = @fopen($tmpfilename,"w")))
{
// Script already running - abort
return 0;
}

// Obtain an exlcusive lock on file
// (If script is running this will fail)
if (!@flock( $tmpfile, LOCK_EX | LOCK_NB, &$wouldblock) || $wouldblock)
{
// Script already running - abort
@fclose($tmpfile);
return 0;
}

This code above creates an exclusive lock on a certain filename. The exclusive lock will automatically get released by the operating system once the script terminates. If we cannot successfuly obtain a lock, it means the script is already running in another thread, in which case we abort.

In your keep-alive script, where you wish to monitor the status of the worker script, you can try to obtain an exlcusive lock on the filename to determine whether or not the file is running:

function IsScriptRunning()
{
// Open PID file
$tmpfilename = "/var/run/myscript.pid";
if (!($tmpfile = @fopen($tmpfilename,"r")))
{
// Script not running
return 0;
}

// Obtain an exlcusive lock on file
// (If script is running this will fail)
$not_running = flock( $tmpfile, LOCK_EX | LOCK_NB, &$wouldblock);

// Release lock if successful
if ($not_running) flock($tmpfile, LOCK_UN);

// Close file
@fclose($tmpfile);

// Return result
return !$not_running || $wouldblock;
}

Mike Peters, 04-19-2010
To check if a shell script is already running, you can use this:

#!/bin/sh

# Already running?
if [ -f "/usr/tmp/myscript.pid" ]
then
p=$(cat /usr/tmp/myscript.pid)
a=$(ps -p $p | grep "myscript" | wc -l)
a=$(echo $a | awk '{print $1}')
if [ "$a" != "0" ]
then
echo "ERROR: MyScript is already running"
exit
fi
fi

# Write our own PID
echo $$ > /usr/tmp/myscript.pid

# Do something useful
# ...

# Remove pid file
rm /usr/tmp/myscript.pid
Enjoyed this post?

Subscribe Now to receive new posts via Email as soon as they come out.

 Comments
Post your comments












Note: No link spamming! If your message contains link/s, it will NOT be published on the site before manually approved by one of our moderators.



About Us  |  Contact us  |  Privacy Policy  |  Terms & Conditions