这是我有一段时间想知道的事情,并决定询问它.
我们有函数getmypid(),它将返回当前脚本进程id.是否有某种功能,如
在php中checkifpidexists()?我的意思是内置的,而不是一些批处理脚本解决方案.
有没有办法改变脚本pid?
一些澄清:
我想检查一个pid是否存在,看看脚本是否已经运行,所以它不再运行,如果你愿意的话,可以使用faux cron job.
我想改变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';
}