【发布时间】:2010-12-11 23:56:33
【问题描述】:
这是我一直想知道并决定询问它的事情。
我们有函数 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';
}
【问题讨论】:
-
“所以我可以将脚本 pid 设置为非常高的值,例如 60000 并硬编码该值”——假设您可以设置 PID 是有缺陷的。这种方法行不通。