[lug] Polling a file under linux

Ed Hill ed at eh3.com
Mon Apr 21 11:22:04 MDT 2003

On Mon, 2003-04-21 at 10:57, Rob Judd wrote:
> I have a C/C++ application that has to connect to an IP address every few
> minutes/seconds (exact timing is not yet clear).  The IP address may
> change as the application is running, and the exact address is stored in
> /etc/myapp.config
> Since this file may change at any time I have to check it before each
> connection.  It seems to me that my options are
> 1. read the contents of the file before every connection
> 2. stat the file before every connection
> both of these are rather expensive, especially if connections are made
> several times a second.
> Is there a better way to poll a file to see when it changes?  (This is in
> C or C++)

The program that you describe sounds like a typical daemon--something
thats running more-or-less continually and has a config file.  The
ages-old Un*x solution for this problem is to *NOT* poll the config
file.  Instead, the program or user that has modified the config file
must then send a signal ("kill -HUP [PID]") to the daemon to tell it to
re-read the config file.  The daemon has previously registered one or
more signal handlers that then (re-)read the config file and (re-)set
any connections, etc. while keeping any needed state.

This solves two problems:

  1) you don't waste lots of time/effort polling, and

  2) the potential *RACE CONDITION* of having a partially-edited 
     config file is (largely) avoided.

Think about it.  The second problem is non-trivial.  While a config file
is being edited, it could easily contain incomplete information.


  man 2 kill
  man 2 signal

for info on registering signal handlers.  Theres plenty of documentation
and examples of this on the web.


Edward H. Hill III, PhD 
Post-Doctoral Researcher
Division of ESE, Colorado School of Mines, Golden, CO 80401
Email: ed at eh3.com  ehill at mines.edu
Phone: 303-273-3483
URLs:  http://cesep.mines.edu/people/hill.htm  http://eh3.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20030421/5688db84/attachment.pgp>

More information about the LUG mailing list