Software, Languages, PHP
PHP: One Instance
Suppose you have a script in PHP that you only ever want to only ever run one instance of.
For example:
- Maintenance script (repair,optimise)
- Update script (crawler)
- Server
These types of scripts need only to be launched once, and more could be counter productive or even dangerous.
The simplest way to stop multiple instances is to check to see if the last running script is still running.
- function isPidRunning( $pid )
- {
- if( $pid )
- {
- $cmd = "ps -p ". (int)$pid;
- $ps=shell_exec( $cmd );
- $ps=explode("n", $ps);
- if(count($ps)>=3)
- {
- return true;
- }
- }
- return false;
- }
- function pidCheck( $name, $version )
- {
- $pid = getmypid();
- if( $pid !== false )
- {
- $pidFile = dirname( __FILE__ ) . '/pid/' . $name . '-' . $version . '.pid';
- if( file_exists( $pidFile ))
- {
- $oldPid = file_get_contents( $pidFile );
- }
- else
- {
- $oldPid = '';
- }
- if( !isPidRunning( $oldPid ) )
- {
- file_put_contents( $pidFile, $pid );
- }
- else
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- return true;
- }
Function file_put_contents() requires a minimum PHP5, however you can use PHP Compat to achieve same functionality.
- if( !pidCheck( $applicationName, $applicationVersion ))
- {
- die('');
- }
You will need to create a folder called pid in the location of script that is running this. The pid folder will require write permission for the user calling the script.
This code can be used in multiple scripts, as long as you supply different $applicationName and/or $applicationVersion strings.
If you plan on using this code in multiple scripts, you would be best off putting the functions isPidRunning and pidCheck into a separate file and using include_once to include their functionality.
Update 22 May 2007: Minor correction to the source code