PHP process id and unique

I want to run a php script in the background and save its PID in the database. So I can check if a particular script is working or not (later).

We can use getmypidto get the current PID.

But according to the PHP manual

Process identifiers are not unique; therefore, they are a weak source of entropy. We recommend that you do not rely on pids in security-dependent contexts.

... and I cannot rely on PID.

My second idea is to save the time created by the process into the database.

How can I get the current script time? And later, how can I compare with tasklist to check if a particular script is working?

I am running a shared host, windows / linux environment.

+3
source share
2

. PHP CLI, PID ( , 2 PID ) grep ps -ax, , . - , PID.

+1

php.net/getmypid

cli.

script /usr/bin/PHP .php.

, nohup /usr/bin/PHP .php > nohup.out & nohup .

#!/usr/bin/php 
<?php 

if ( PHP_SAPI !== 'cli' ) {
    die( "Cmd line access only!\n" );
}

define( 'LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );  // can also use /tmp
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 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; 

} 
?>
+1

Source: https://habr.com/ru/post/1661436/


All Articles