加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

PHP进程ID和唯一

发布时间:2021-08-28 03:47:26 所属栏目:大数据 来源: https://www.jb51.cc
导读:我想在后台运行PHP脚本并将其PID存储在数据库中.这样我就可以检查特定脚本是否正在运行(稍后). 我们可以使用getmypid来获取当前的PID. 但是根据PHP手册 Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on

我想在后台运行PHP脚本并将其PID存储在数据库中.这样我就可以检查特定脚本是否正在运行(稍后).

我们可以使用getmypid来获取当前的PID.

但是根据PHP手册

Process IDs are not unique, thus they are a weak entropy source. We
recommend against relying on pids in security-dependent contexts.

……我不能依赖PID.

我的第二个想法是将进程创建时间存储到数据库中.

如何获取当前脚本创建的时间?以后如何与tasklist进行比较以检查特定脚本是否正在运行?

我在共享主机,Windows / Linux环境中运行.

解决方法:

从php.net/getmypid起

几乎没有修改来禁用非cli访问.

脚本可以使用/usr/bin/PHP script.PHP执行.

另外使用nohup /usr/bin/PHP script.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'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; 

} 
?>

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读