tags:

views:

410

answers:

3

Hi,

I am currently watching an XML file from log4j output. I have a custom viewer that displays the log-output in GUI. I need to watch this file as to when it gets updated so that the GUI can re-parse and update itself. In C# there is a FileWatcher concept so on Windows no-probs, but what options do i have using C on Linux.

Is there a standard way of doing this on both unix and linux flavours (POSIX maybe)?

Thanks

+6  A: 

Are you looking for something like inotify ?

Alternatively you could poll the file using stat.

John T
That meets my needs perfectly, but i think i will have to re-invent the wheel and code it using standard C APIs. So is there any chance that i can do it using simple fstat and stat APIs?
You might want to clarify that ... If inotify sounds like what you need, and you're on Linux, why can't you just use it?
unwind
+6  A: 

John mentioned the two main routes you can take for watching files under Unix/Linux systems: notification and polling.

Notification is when the system itself (usually the kernel) triggers a message to registered applications whenever the file is accessed or written to. This approach requires a compliant system and might not be available on older machines.

The primary implementation of notification under Linux is inotify, which is built into kernels 2.6.13 and later and can be patched into 2.6.12 and earlier. There's a nice IBM guide on using inotify as well as a basic set of tools and C library for accessing inotify.

Polling is when your program repeatedly checks a file at intervals to see if anything about that file - its size, last modification time, owner, etc. - has been changed.

There's no standard implementation of this, as it's written on a program-level rather than system-level basis, although the system call poll exists and seems to do something useful for this purpose (the man page says it's similar to select, and it waits for an event to become available on a file descriptor). You could also take the more basic approach with stat and do your checking on your own.

Tim
thanks for the explanation
I doubt that poll() will help. It sounds like you have misunderstood what poll() does. Unless you mean to use it *with* inotify.
Thomas
To clarify: poll() can only tell you stuff like "if I read() from this file now, will that block?" or "Wait for max 3 seconds or until I can read (without read() blocking) from at least one of these file descriptors".
Thomas
Thomas: thanks for the clarification.
Tim
A: 

If you want something more portable than inotify, which is a Linux-ism, look into the File Alteration Monitor, which is older and more portable technology, but can be less performant. On the other hand, it does something useful with NFS-mounted filesystems, which depending on your application could be important.

Norman Ramsey
thanks for the suggestion, particularly as it is kernel agnostic and probably works with NFS mounted systems.