What's the fastest way using lsof to find a single open file?

jjclarkson picture jjclarkson · Mar 26, 2010 · Viewed 8.6k times · Source

I'm trying to test a single file if it is open using lsof. Is there a faster way than this?

$result = exec('lsof | grep filename | wc -l');

if($result > 0) {
    //file is open
}

I'm thinking their must be a way to just test for one file if you know the filename. All I really need is a true or false.

Answer

R Samuel Klatchko picture R Samuel Klatchko · Mar 26, 2010

I found a much better way. With lsof (tested on version 4.63), you can directly query a specific file:

if lsof filename > /dev/null; then
    # file is open
fi