Tutorial :Detecting changes to an open file



Question:

Suppose I have an open file. How can I detect when the file is changed by another program in the background. Some text editors can detect and update the open file if it is changed by another process.

I'm specifically asking for this with C under Linux(this seems to be OS dependent).


Solution:1

If you don't want to poll the file using stat, and don't mind being Linux-specific, then you can use the inotify API. Your kernel needs to be 2.6.13 or newer and glibc 2.4 or newer (which they will be if you're targeting anything from the past 2 or 3 years). The API basically gives you a file descriptor that you can poll or select, and read to get information about modified files. If your application is interactive, like an editor, then it will typically have some sort of event loop that calls select or poll, and can watch your inotify file descriptor for events.

Using inotify is generally preferable stat, because you get notifications immediately and you don't waste time and disk I/O polling when the file isn't changing. The downside is that might not work over NFS or other networked file systems, and it's not portable.

This page at IBM Developerworks gives some example C code, and the man page is the definitive reference.


Solution:2

use stat function. Example in the page.


Solution:3

Text editors I've seen on Windows and Linux have done it the same way: they don't check to see whether the file has actually changed, they just looking at the file's stat mtime.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »