1

I have this minimal example 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);

The problem is that when I run this script twice, then the second instance will block on the flock() function call, supposedly because the first one did not release the file lock.

When I exec() a different command instead of eval `ssh-agent -s`, such as git --version, then everything seems to work fine.

Does anyone know what the problem is? Is it a bug in PHP or my poor understanding of flock()?

Pieter van den Ham
  • 4,381
  • 3
  • 26
  • 41

1 Answers1

0

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.

Pieter van den Ham
  • 4,381
  • 3
  • 26
  • 41