Check if a file is open by another process in PHP (Linux/UNIX)

The PHP flock() function is good when the file locking method is used the same way by all programs that will lock the file.

However, you can’t check if any process in the system is actually using the file or not. If you for example are monitoring an incoming ftp folder, you don’t want to start processing a file until the file is completely tranferred (i.e. wait until the ftp daemon is no longer having the file open).

The following code illustrates how the command lsof can be used for the purpose: 

<?php
$filename = "locktest.txt";
$directory = ".";
while (1) {
        $result = exec("lsof +D $directory | grep -c -i $filename");
        if ($result == "0") {
                echo "$directory/$filename is NOT open ($result)\n";
        } else {
                echo "$directory/$filename IS OPEN ($result)\n";
        }
        sleep(1);
};
?>

 
1 reply
  1. Junaid
    Junaid says:

    Hello,

    Thanks for a very good example exactly what I needed.

    I implemeneted it and facing the following issue

    lsof: WARNING: can’t stat() fuse.gvfs-fuse-daemon file system /home/junaid/.gvfs
    Output information may be incomplete.

    can you guide me on how to fix this?

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

three × two =