Is there a simple way to detect when a file for writing is closed? I have a process that kicks out a new file every 5 seconds. I can not change the code for that process. I am writing another process to analyze the contents of each file immediately when it is created. Is there a simple way to watch a certain directory to see when a file is no longer opened for writing? I'm hoping for some sort of Linux command.
-
What language? What context is each process called? – IAbstract Apr 14 '10 at 16:34
-
In order to have extra time to process the file, consider creating a file system in memory - that ought to speed things up. – Hamish Grubijan Apr 14 '10 at 16:36
-
Any language. I was hoping for something in bash, but anything will do. The process is a command-line utility that is executed directly by the user and runs for several hours. – User1 Apr 14 '10 at 16:40
5 Answers
If you know there is some particular text (line) in the file that indicates completion of writing you could easily watch for that using commands like grep
Also, you can use fuser
command to find out if a file is in use.

- 20,383
- 7
- 59
- 72
As you are using linux as your platform you might want to have a look at the inotify syscalls. When monitoring the directory were the output files are written you will get open/close events for the files created there.
If you want to integrate this into a shell script have a look at inotifywait which is part of the inotify-tools.

- 2,778
- 2
- 20
- 26
you can put something on top of strace to raise your events.
try:
strace ls 2>&1 | grep "close\|open"
Using inotify is also a good idea, but will probably require more coding to get what you need.

- 31,280
- 18
- 64
- 87
-
+1 sounds like a great idea. However, the pipe doesn't seem to work. I think strace is running on "command | grep fclose" instead of just "command". Any hints? – User1 Apr 14 '10 at 19:30
-
oops, I updated the answer to have a working example :). strace prints to stderr by default. – Omry Yadan Apr 15 '10 at 09:16
-
that seems to have worked. It's very cool that I can also see which shared libraries are used by the executable. Thank you! – User1 Apr 15 '10 at 18:39
You could lock the contents of your file until you're done using it.

- 1
- 1

- 339,232
- 124
- 596
- 636
If you know the process ID of the process that is writing the files, you can watch /proc/<pid>/fd/
to see which files it has open.

- 233,326
- 40
- 323
- 462