How to check if a file is opened in Linux?

Darshit Patel picture Darshit Patel · Jun 19, 2015 · Viewed 14.8k times · Source

The thing is, I want to track if a user tries to open a file on a shared account. I'm looking for any record/technique that helps me know if the concerned file is opened, at run time.

I want to create a script which monitors if the file is open, and if it is, I want it to send an alert to a particular email address. The file I'm thinking of is a regular file.

I tried using lsof | grep filename for checking if a file is open in gedit, but the command doesn't return anything.

Actually, I'm trying this for a pet project, and thus the question.

Answer

Thomas Schallar picture Thomas Schallar · Jul 19, 2017

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.