Code Tips and Snippets

Not yet member?
Click here to register.
Only members can post comments
Allow only a single instance of a php script to run at the same time
Posted by pk on Sunday, September 21 2014 - 16:37:43
4 stars levelphp languageLinux operating system

What a good idea to administer a Linux server by writing php scripts instead of shell scripts ...

We have already seen how to run php scripts with suid root permission

Frequently, we need to run a script that must not be run several times at the same time...we say that we want to run only a single instance of the script at the same time.

We will use php classes to achieve that... especially the fact that when a script ends, the destructor of instancied objects is automatically called.

Let's get right down to business by unveiling a sample code that you can adapt to your needs.

class SingleInstanceProcess
	private	$pid_file;
	public	$is_ok;

	function __construct()
		global $argv;

		$this->is_ok	= 0;
		$my_name		= basename($argv[0]);
		$this->pid_file	= "/tmp/$";
		$pid			= getmypid();				if (!$pid) exit(1);

		$this->is_ok	= 1;
		if (file_exists($this->pid_file))
			$old_pid	= file_get_contents($this->pid_file);
			$cmd		= "ps -Cp $old_pid | grep $my_name";
			$result		= trim(`$cmd`);
			$t_result	= explode(" ",$result);
			$result		= $t_result[0]; 
			if ($old_pid==$result)			// Old process is running or accepable issue:
			{								// 			If the old process was killed ( e.g. kill -9  or power failure and /tmp not cleaned)
				$this->is_ok	= 0;		//			and another program with excactly the same name is running
				return;						//			with exactly the same pid as the previous killed process... 
											//			(practicaly, the probability that this happens is negligible.)
			}								//			we may wrongly suppose that an instance is running ...
		file_put_contents($this->pid_file, $pid);

	public function __destruct()
		if($this->is_ok && file_exists($this->pid_file))	unlink($this->pid_file);

$single_instance_process = new SingleInstanceProcess;

if (!$single_instance_process->is_ok) exit(0);

By naming this script single_instance.php

You just have to do an include in your script, and it will only run if there is no another instance of that script already running!

< ?php
// here my script whatever.php

include "/path/single_instance.php";

//  my code here

? >


yakpro rulez!

Site has been updated on Wednesday, January 19 2022 - 09:43:57