4

I would like to asynchronously monitor a file for any changes. That is I would like to have a call back (possibly from kernel) in my program when the file has been modified/deleted. The file is just a plain text file. I know one can do this using a polling mechanism, but I am looking for an event based solution. I read about inotify, but looks like it needs patching of my kernel.

If the solution is POSIX compliant, its even better.

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
vinodkone
  • 2,731
  • 4
  • 22
  • 21

3 Answers3

8

Inotify was merged to the Linux kernel way back in 2005, so unless you're in a very old system, you should be able to use it out of the box.

I don't think there exists a POSIX compliant solution for this. Mac OS X has FSEvents.

Also check the man page for inotify.

EDIT:

Don't know about your constraints and/or requirements, but there is also GFileMonitor if you use Glib (the C++ binding is glibmm) and QFileSystemWatcher is you use Qt. Those are probably more cross-platform friendly.

Gustavo Giráldez
  • 2,610
  • 18
  • 12
  • 2
    Here is a small example of using `inotify` to wait for file to appear, if it helps - http://lazarenko.me/tips-and-tricks/waiting-for-the-file-to-appear-in-linux-using-inotify It can be easily tuned to watch for file changes. –  Aug 04 '11 at 18:40
1

SGI's fam has been ported to several Unixes. There's also gamin.

ninjalj
  • 42,493
  • 9
  • 106
  • 148
0

1)

write a device driver that creates a file called /dev/special_file.

symlink your plain text file to /dev/special file

intercept the low-level read/write operations to modify the real text file, called /path/to/text.txt, then generate the callback via signals or some type of interprocess comm to whatever process you want.

2)

have a process open your text file and just sit and wait. use select() to detect when that file has been modified, then do callback routine.

Harry Seward
  • 147
  • 1