[lug] Polling a file under linux

D. Stimits stimits at attbi.com
Mon Apr 21 14:58:42 MDT 2003

Rob Judd wrote:

> On Mon, 21 Apr 2003, Ed Hill wrote:
> >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
> Yep, that's the general situation.
> >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.
> This is a great suggestion, thanks.  However, it brings to mind the
> /etc/resolv.conf file.  This is (potentially) used by several
> applications, so it becomes infeasible to use the above method.  Does
> anyone know how applications use that file?

As a slight twist on this, if your application has a name for the IP 
address, then /etc/hosts, if modified will always be the right IP 
address when connecting by name. One possibly major headache of this 
scheme is that only root can update /etc/hosts.

D. Stimits, stimits AT attbi DOT com

More information about the LUG mailing list