PHP检查进程ID
这是我有一段时间想知道的事情,并决定询问它.
我们有函数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'; }
在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由OS授予,并且不能保留进程ID.你可以编写你的守护进程来尊重pid文件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |