Home > Mobile >  PHP 8.1 not release flock after calling exec
PHP 8.1 not release flock after calling exec

Time:04-20

i have this minimal code for PHP 8.1

<?php
ini_set('display_errors', 'on');
if(($fp = @fopen(__DIR__ . '/test.some', 'r ')) === false){
    $fp = fopen(__DIR__ . '/test.some', 'c ');
}
flock($fp, LOCK_EX);
exec('eval `ssh-agent -s`', $output1, $resultCode1);
var_dump($output1, $resultCode1);
fclose($fp);

Problem is that when i run script twice, than second run will freeze on flock because first one did not released a lock.

Does anyone know where is problem? Is it PHP bug or my poor knowlege?

When i use eg. 'git --version' instead of 'eval ssh-agent -s' than is everything ok.

CodePudding user response:

Normally, when a process exits all file locks are released automatically (source). However, ssh-agent is forked as a background process, which causes it to inherit all file locks from the parent process.

This behavior can be confirmed by running sudo fuser -v /tmp/test.some, which shows us that ssh-agent inherited the lock.

                     USER        PID ACCESS COMMAND
/tmp/test.some:      testuser    19834 F.... ssh-agent
                     testuser    19873 F.... php8.1

Adding flock($fp, LOCK_UN), as suggested in the comments by Pran Joseph, indeed fixes this issue.

  • Related