Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting changes to an open file

Tags:

c

file

linux

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).

like image 497
Atilla Filiz Avatar asked Jan 22 '09 11:01

Atilla Filiz


2 Answers

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.

like image 139
Doug Avatar answered Sep 21 '22 21:09

Doug


use stat function. Example in the page.

like image 27
Aif Avatar answered Sep 22 '22 21:09

Aif