我想在后台运行一个 php 脚本并将其 PID 存储在数据库中。这样我就可以检查特定脚本是否正在运行(稍后)。
我们可以用getmypid
获取当前PID。
但根据 PHP 手册
进程 ID 不是唯一的,因此它们是弱熵源。我们
建议不要在依赖安全的上下文中依赖 pid。
...而且我不能依赖 PID。
我的第二个想法是将进程创建时间存储到数据库中。
如何获取当前脚本的创建时间?稍后我如何与任务列表进行比较来检查特定脚本是否正在运行?
我在共享主机、windows/linux 环境上运行。
From php.net/getmypid http://php.net/manual/en/function.getmypid.php#93753
只需稍作修改即可禁用非 cli 访问。
脚本可以使用执行/usr/bin/php script.php
.
另外使用nohup /usr/bin/php script.php > nohup.out &
启动一个nohup https://en.wikipedia.org/wiki/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;
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)