gpt4 book ai didi

PHP 检查进程 ID

转载 作者:可可西里 更新时间:2023-11-01 12:25:35 25 4
gpt4 key购买 nike

这是我想知道了一段时间并决定问一问的事情。

我们有函数 getmypid() ,它会返回当前脚本的进程 ID。是否有某种功能,例如

checkifpidexists() 在 PHP 中?我的意思是内置解决方案,而不是一些批处理脚本解决方案。

有没有办法更改脚本 pid?

一些说明:

我想检查 pid 是否存在以查看脚本是否已经在运行,所以它不会再次运行,如果你愿意的话,可以伪造 cron 作业。

我想更改 pid 的原因是我可以将脚本 pid 设置为非常高的值,例如 60000 并对该值进行硬编码,因此该脚本只能在该 pid 上运行,因此它只会运行 1 个实例

编辑----

为了帮助其他人解决这个问题,我创建了这个类:

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;
}

}

然后你像这样使用它:

$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';
}

最佳答案

在 Linux 中,您会查看/proc。

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

在 Windows 中,您可以使用 shell_exec() tasklist.exe,这会找到匹配的进程 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 ];
}

我相信您想要做的是维护一个 PID 文件。在我编写的守护进程中,它们检查配置文件,查找 pid 文件的实例,从 pid 文件中获取 pid,检查/proc/$pid 是否存在,如果不存在,则删除 pid文件。

   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 );

进程 ID 由操作系统授予,不能保留进程 ID。你会编写你的守护进程来尊重 pid 文件。

关于PHP 检查进程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1656350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com