你可以用一个锁文件。PHP的
flock()
函数为Unix的
flock
如果您没有显式地释放它们,那么当持有它们的进程终止时,操作系统将自动为您释放这些锁,即使它异常终止。
您还可以遵循松散的Unix约定,将锁文件设为“PID文件”——也就是说,在获取文件的锁时,让脚本将其PID写入该文件。即使您从未在脚本中阅读过此内容,但如果您的脚本挂起或变得疯狂,并且您希望找到它的PID以便手动杀死它,则会很方便。
#!/usr/bin/php
$lock_file = fopen('path/to/yourlock.pid', 'c');
$got_lock = flock($lock_file, LOCK_EX | LOCK_NB, $wouldblock);
if ($lock_file === false || (!$got_lock && !$wouldblock)) {
throw new Exception(
"Unexpected error opening or locking lock file. Perhaps you " .
"don't have permission to write to the lock file or its " .
"containing directory?"
);
}
else if (!$got_lock && $wouldblock) {
exit("Another instance is already running; terminating.\n");
}
// Lock acquired; let's write our PID to the lock file for the convenience
// of humans who may wish to terminate the script.
ftruncate($lock_file, 0);
fwrite($lock_file, getmypid() . "\n");
/*
The main body of your script goes here.
*/
echo "Hello, world!";
// All done; we blank the PID file and explicitly release the lock
// (although this should be unnecessary) before terminating.
ftruncate($lock_file, 0);
flock($lock_file, LOCK_UN);
只要把你的锁文件的路径设置到你喜欢的任何地方。