I have some code with process forks (pcntl_fork()
) and lockfile to distribute tasks between the forks.
I'm checking if a task available for current fork with lockfile using flock()
:
$pid = getmypid();
$result = false;
$file = fopen($this->lockFile, 'a+b');
do {
$lock = flock($file, LOCK_EX);
} while (!$lock);
echo "$pid Locked";
fseek($file, 0);
$content = @fread($file, filesize($this->lockFile));
$locked = explode(PHP_EOL, $content);
if (!in_array($package, $locked)) {
fwrite($file, PHP_EOL . $package);
fflush($file);
$result = true;
}
flock($file, LOCK_UN);
fclose($file);
echo "$pid Released";
return $result;
Sometimes I'm getting two output lines with text "Locked" without "Released" line between them. In this case two different forks doing the same task when I want them to do smthng different.