Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check Process ID

Tags:

php

process

This is something i have wondered for a while and decided to ask about it.

We have the function getmypid() which will return the current scripts process id. Is there some kind of function such as

checkifpidexists() in php? I mean a inbuilt one and not some batch script solution.

And is there a way to change a scripts pid?

Some clarification:

I want to check if a pid exists to see if the script is already running so it dont run again, faux cron job if you will.

The reason i wanted to change the pid is so i can set the script pid to something really high such as 60000 and hard code that value so this script can only run on that pid so only 1 instance of it would run

EDIT----

To help anyone else with this proplem, i have created this class:

class instance {

    private $lock_file = '';
    private $is_running = false;

    public function __construct($id = __FILE__) {

        $id = md5($id);

        $this->lock_file = sys_get_temp_dir() . $id;

        if (file_exists($this->lock_file)) {
            $this->is_running = true;
        } else {
            $file = fopen($this->lock_file, 'w');
            fclose($file);
        }
    }

    public function __destruct() {
        if (file_exists($this->lock_file) && !$this->is_running) {
            unlink($this->lock_file);
        }
    }

    public function is_running() {
        return $this->is_running;
    }

}

and you use it like so:

$instance = new instance('abcd'); // the argument is optional as it defaults to __FILE__

if ($instance->is_running()) {
    echo 'file already running';    
} else {
    echo 'file not running';
}
like image 875
Ozzy Avatar asked Nov 01 '09 04:11

Ozzy


2 Answers

In linux, you would look at /proc.

return file_exists( "/proc/$pid" );

In Windows you could shell_exec() tasklist.exe, and that would find a matching process id:

$processes = explode( "\n", shell_exec( "tasklist.exe" ));
foreach( $processes as $process )
{
     if( strpos( "Image Name", $process ) === 0
       || strpos( "===", $process ) === 0 )
          continue;
     $matches = false;
     preg_match( "/(.*?)\s+(\d+).*$/", $process, $matches );
     $pid = $matches[ 2 ];
}

I believe what you want to do is maintain a PID file. In the daemons I've written, they check a config file, look for an instance of a pid file, get the pid out of the pid file, check to see if /proc/$pid exists, and if not, delete the pid file.

   if( file_exists("/tmp/daemon.pid"))
   {
       $pid = file_get_contents( "/tmp/daemon.pid" );
       if( file_exists( "/proc/$pid" ))
       {
           error_log( "found a running instance, exiting.");
           exit(1);
       }
       else
       {
           error_log( "previous process exited without cleaning pidfile, removing" );
           unlink( "/tmp/daemon.pid" );
       }
   }
   $h = fopen("/tmp/daemon.pid", 'w');
   if( $h ) fwrite( $h, getmypid() );
   fclose( $h );

Process IDs are granted by the OS and one cannot reserve a process id. You would write your daemon to respect the pid file.

like image 135
memnoch_proxy Avatar answered Oct 13 '22 20:10

memnoch_proxy


For checking if a PID exist on a windows machine i use:

function pidExists($pid)
{
    exec('TASKLIST /NH /FO "CSV" /FI "PID eq '.$pid.'"', $outputA );
    $outputB = explode( '","', $outputA[0] );
    return isset($outputB[1])?true:false;
}

Note that $outputB[0] contains a messages that pid can't be found, if the pid indeed doesn't exists! So to validate i use the second argument.

EDIT:

To expand on this, its also possible to dynamically spawn scripts within windows in the background using powershell like so:

    // this function builds an argument list to parse into the newly spawned script. 
    // which can be accessed through the superglobal  global $argv;
    function buildArgList( array $arguments){
     return ' '. implode(' ', $arguments) .' ';
    }

    $arguments = buildArgList(['argument1','argument2','argument3']);
    $windowstyle = 'normal'; // or you can use hidden to hide the CLI

    pclose(popen("powershell start-process -FilePath '" . PHP_BINARY . "' -ArgumentList '-f\"" . $file . " " . $arguments . "\"' -WindowStyle " . $windowstyle,"r"));   

The script you spawn can then use: cli_set_process_title to set that process's title to some unique hash.

within the parent that spawned the child process you can use the following code to find that process within the tasklist using its windowtitle searching for the uniquehash.

exec('TASKLIST /NH /FO "CSV" /FI "windowtitle eq ' . escapeshellarg($uniquehash) . '"', $output );

When combined with a database you can essentially build a workermanager communicating between different php scripts.

like image 31
spoofie Avatar answered Oct 13 '22 21:10

spoofie