make lock-file code more reusable

This commit is contained in:
Dylan K. Taylor
2019-08-25 18:50:33 +01:00
parent 5c1f1f00cb
commit 6e692d76d5
2 changed files with 53 additions and 10 deletions

View File

@ -24,6 +24,7 @@ declare(strict_types=1);
namespace pocketmine {
use pocketmine\thread\ThreadManager;
use pocketmine\utils\Filesystem;
use pocketmine\utils\MainLogger;
use pocketmine\utils\Process;
use pocketmine\utils\ServerKiller;
@ -207,20 +208,12 @@ namespace pocketmine {
mkdir($dataPath, 0777, true);
}
define('pocketmine\LOCK_FILE', fopen($dataPath . 'server.lock', "a+b"));
if(!flock(\pocketmine\LOCK_FILE, LOCK_EX | LOCK_NB)){
//wait for a shared lock to avoid race conditions if two servers started at the same time - this makes sure the
//other server wrote its PID and released exclusive lock before we get our lock
flock(\pocketmine\LOCK_FILE, LOCK_SH);
$pid = stream_get_contents(\pocketmine\LOCK_FILE);
$lockFilePath = $dataPath . '/server.lock';
if(($pid = Filesystem::createLockFile($lockFilePath)) !== null){
critical_error("Another " . \pocketmine\NAME . " instance (PID $pid) is already using this folder (" . realpath($dataPath) . ").");
critical_error("Please stop the other server first before running a new one.");
exit(1);
}
ftruncate(\pocketmine\LOCK_FILE, 0);
fwrite(\pocketmine\LOCK_FILE, (string) getmypid());
fflush(\pocketmine\LOCK_FILE);
flock(\pocketmine\LOCK_FILE, LOCK_SH); //prevent acquiring an exclusive lock from another process, but allow reading
//Logger has a dependency on timezone
Timezone::init();