How can you set the timing of lsof to sub 1 second? On lsof -r (repeat mode), is the minimum value 1 second? Is there a way to have a continuous monitoring with lsof without having intervals between 2 consecutive lsof command in order to check which user had accessed specific file?
2 Answers
If you dont have inotifywait installed, (which is ideal for this), then you can get closer to real-time if you combine lsof with watch:
$ watch -n0.1 lsof
This updates every 0.1 of a second.
- 481
To monitor in "real time" any file accesses under the current directory, open a terminal and run:
inotifywait -r -m -e access --format '%w%f' . | while IFS='' read -r fname; do [ -f "$fname" ] && lsof "$fname"; done
Or, as spread out over multiple lines:
inotifywait -r -m -e access --format '%w%f' . | while IFS='' read -r fname
do
[ -f "$fname" ] && lsof "$fname"
done
This requires an OS, such as linux, which supports inotifywait.
The body of the while loop can be replaced with anything that suits your purpose.
The meaning of the options to inotifywait are:
-rMonitor recursively through subdirectories.
-mMonitor continuously.
-e accessMonitor ACCESS events. There are many possible events that might be of interest but this appears to be most closely matched to what you asked for.
--format '%w%f'Write the path and file of each accessed file to standard out.
.Monitor the current directory,
..
Limitation
The above code does not handle file names which contain newline characters. To handle that, one needs to use inotifywait's -csv option along with more code that understands the subtleties of CSV format.
- 17,343