(PHP 4, PHP 5)
getmypid — Prozess-Id eines Scripts
Liefert die Prozess-ID unter der das Skript ausgeführt wird.
Liefert die Prozess-ID unter der das Skript ausgeführt wird, oder FALSE bei Fehlern
Prozess-IDs sind nicht eindeutig, sie sind daher eine schwache Entropiequelle. Wir raten davon ab sich in sicherheitsrelevanten Bereichen auf Prozess-IDs zu verlassen.
Based on what james at voodoo dot co dot uk said, but modified for CLI scripts (ie: there is no $_SERVER).
<?php
/**
* Check for a current process by filename
* @param $file[optional] Filename
* @return Boolean
*/
function processExists($file = false) {
$exists = false;
$file = $file ? $file : __FILE__;
// Check if file is in process list
exec("ps -C $file -o pid=", $pids);
if (count($pids) > 1) {
$exists = true;
}
return $exists;
}
?>
The 'ps' command has an option that can make filtering for a specific process more efficient. Using this the work of looking for matching processes can be made neater:
<?php
/*
Return an array of the pids of the processes that are running for the specific command
e.g.
returnPids('myprocess.php');
*/
function returnPids($command) {
exec("ps -C $command -o pid=",$pids);
foreach ($pids as $key=>$value) $pids[$key]=trim($value);
return $pids;
}
/*
Returns an array of the pids for processes that are like me, i.e. my program running
*/
function returnMyPids() {
return returnPids(basename($_SERVER["SCRIPT_NAME"]));
}
?>
e.g. to bomb out if I'm running already
if (count(returnMyPids())>1) exit;
We also had this challenge in our company to prevent a php script in a cron job from overlapping each other.
We made this solution
<?php
// Initialize variables
$found = 0;
$file = basename(__FILE__);
$commands = array();
// Get running processes.
exec("ps w", $commands);
// If processes are found
if (count($commands) > 0) {
foreach ($commands as $command) {
if (strpos($command, $file) === false) {
// Do nothin'
}
else {
// Let's count how many times the file is found.
$found++;
}
}
}
// If the instance of the file is found more than once.
if ($found > 1) {
echo "Another process is running.\n";
die();
}
/**
*
* Regular process here...
*
*/
?>
Looking to create a lock-file mechanism for a cmd-line script?
Enjoy!
#!/usr/bin/php
<?php
define( 'LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );
if( isLocked() ) die( "Already running.\n" );
# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);
unlink( LOCK_FILE );
exit(0);
function isLocked()
{
# If lock file exists, check if stale. If exists and is not stale, return TRUE
# Else, create lock file and return FALSE.
if( file_exists( LOCK_FILE ) )
{
# check if it's stale
$lockingPID = trim( file_get_contents( LOCK_FILE ) );
# Get all active PIDs.
$pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );
# If PID is still active, return true
if( in_array( $lockingPID, $pids ) ) return true;
# Lock-file is stale, so kill it. Then move on to re-creating it.
echo "Removing stale lock file.\n";
unlink( LOCK_FILE );
}
file_put_contents( LOCK_FILE, getmypid() . "\n" );
return false;
}
?>
<?php
/*
mixed getpidinfo(mixed pid [, string system_ps_command_options])
this function gets PID-info from system ps command and return it in useful assoc-array,
or return false and trigger warning if PID doesn't exists
$pidifo=getpidinfo(12345);
print_r($pidifo);
Array
(
[USER] => user
[PID] => 12345
[%CPU] => 0.0
[%MEM] => 0.0
[VSZ] => 1720
[RSS] => 8
[TT] => ??
[STAT] => Is
[STARTED] => 6:00PM
[TIME] => 0:00.01
[COMMAND] => php someproces.php > logfile
)
*/
//////////////////////////////////////////////
function getpidinfo($pid, $ps_opt="aux"){
$ps=shell_exec("ps ".$ps_opt."p ".$pid);
$ps=explode("\n", $ps);
if(count($ps)<2){
trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING);
return false;
}
foreach($ps as $key=>$val){
$ps[$key]=explode(" ", ereg_replace(" +", " ", trim($ps[$key])));
}
foreach($ps[0] as $key=>$val){
$pidinfo[$val] = $ps[1][$key];
unset($ps[1][$key]);
}
if(is_array($ps[1])){
$pidinfo[$val].=" ".implode(" ", $ps[1]);
}
return $pidinfo;
}
?>
You can use this function also to avoid more than one instance of your app.
You can also use this class.
http://www.pure-php.de/node/20
Usage:
<?php
inlude("ProcessHandler.class.php");
if(ProcessHandler::isActive()){
die("Already running!\n";);
}else{
ProcessHandler::activate();
//run my app
}
?>
One good use for this is deciding on a concurrency-safe temporary file or directory name. You can be assured that no two processes on the same server have the same PID, so this is enough to avoid collisions. For example:
<?php
$tmpfile = "/tmp/foo_".getmypid();
// Use $tmpfile...
// Use $tmpfile...
// Use $tmpfile...
unlink ($tmpfile);
?>
If you are sharing /tmp over the network (which is odd....) then you can, of course, mix in the PHP server's IP address.