Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

linux

php

lsof

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.

like image 991
jjclarkson Avatar asked Mar 26 '10 21:03

jjclarkson


People also ask

What is lsof command used for?

lsof command stands for List Of Open File. This command provides a list of files that are opened. Basically, it gives the information to find out the files which are opened by which process.

How do I list files open in a particular process?

Simply typing lsof will provide a list of all open files belonging to all active processes.

How can I tell if a file is open in Linux?

The command lsof -t filename shows the IDs of all processes that have the particular file opened. lsof -t filename | wc -w gives you the number of processes currently accessing the file.

What is device in lsof?

$ man 8 lsof | grep -A 10 '^\s\{7\}DEVICE' DEVICE contains the device numbers, separated by commas, for a character special, block special, regular, directory or NFS file; or ``memory'' for a memory file system node under Tru64 UNIX; or the address of the private data area of a Solaris socket stream; or a kernel ...


2 Answers

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
like image 182
R Samuel Klatchko Avatar answered Sep 21 '22 15:09

R Samuel Klatchko


Don't. The answer might change by the time you try to do anything with the result. Instead, try to do whatever you intended to do with the file and handle the "in use" error or "sharing violation".

like image 38
Ben Voigt Avatar answered Sep 21 '22 15:09

Ben Voigt