tags:

views:

82

answers:

6

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.

+1  A: 

You could lock the contents of your file until you're done using it.

Brian R. Bondy
Voluntary locking is advisable.
Hamish Grubijan
+2  A: 

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.

ring bearer
+1  A: 

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.

Frank Meerkötter
+2  A: 

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.

Omry
+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
oops, I updated the answer to have a working example :). strace prints to stderr by default.
Omry
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
for this you can also ldd :)
Omry
+1  A: 

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.

caf
A: 

incron

Ignacio Vazquez-Abrams