我一直想知道的是,我们有一个函数getmypid()可以返回当前脚本的进程ID。是否有类似于checkifpidexists()的函数可用于php中?我的意思是内置的而不是批处理脚本解决方案。
另外,是否有一种方法可以更改脚本的进程ID?
一些明确的说明:
我想检查一个PID是否存在,以查看脚本是否已经在运行中,这样它就不会再次运行,这就像是一个伪cron作业。
我希望更改PID的原因是我可以将脚本PID设置为非常高的值,例如60000,并硬编码该值,以便该脚本只能在该PID上运行,因此只有一个实例会运行。
编辑 - - - -
为了帮助其他人解决这个问题,我创建了这个类:
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';
}