Search code examples
phpfilepinglsof

test if file opened from php is still open


I have a PHP script running on Debian that calls the ping command and redirects the output to a file using exec():

exec('ping -w 5 -c 5 xxx.xxx.xxx.xxx > /var/f/ping/xxx.xxx.xxx.xxx_1436538580.txt &');

The PHP script then has a while loop that scans the /var/f/ping/ folder and checks to see if the ping has finished writing to it. I tried checking the output using:

exec('lsof | grep /var/f/ping/xxx.xxx.xxx.xxx_1436538580.txt');

to see if the file was still open, but it takes lsof about 10-15 seconds to return its results, which is too slow for what we need. Ideally it should be able to check this within 2 or 3 seconds.

Is there a faster/better way to test if the ping has completed?


Solution

  • using grep with lsof is probably the slowest way, as lsof will scan everything. you can narrow down the scope that lsof uses to one directory by doing:

    lsof +D /var/f/ping
    

    or similar.

    there's a good and easy-to-read overview of lsof uses here:

    http://www.thegeekstuff.com/2012/08/lsof-command-examples/

    alternately, you could experiment with:

    http://php.net/manual/en/function.fam-monitor-file.php

    and see if that meets your requirements better.