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.
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.
Simply typing lsof will provide a list of all open files belonging to all active processes.
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.
$ 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 ...
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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With