Sunday, February 1, 2015

Check if another instance / process (by PID) of PHP script running / executed already exists via temporary file lock

If you are trying to make sure your back-end running script will only have a single instance running, you may want to use a script like this.


// ---- SOMEWHERE AT THE TOP OF YOUR SCRIPT -----------
// TRY TO GET EXCLUSIVE LOCK

$fp_pid_pathfilename = "/tmp/your_script_name.php.lock";

$fp_pid_lock = fopen($fp_pid_pathfilename, "w");

// try to get exclusive lock, non-blocking
if (!flock($fp_pid_lock, LOCK_EX|LOCK_NB)) {
	// failed to get lock
	die("Another instance is already running.\n");
} else {
	// got lock, write PID
	fwrite($fp_pid_lock, getmypid());
}

.
.
.


// ---- THEN AT THE END OF THE SCRIPT ------------
// CLOSE OR RELEASE PROCESS PID LOCK

fclose($fp_pid_lock);
unlink($fp_pid_pathfilename);


TIP: Please make sure you store your lock file in /tmp, the reason is simple, most linux server will remove all files/directory for /tmp directory, therefore if you have a sudden power failure, your lock file will not be stuck.

No comments:

Post a Comment