Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Linux C code find conf file(usually in /etc)

Tags:

c

linux

project

I know when I install a Linux app from source ,I execute ./configure --sysconfdir=/etc, then this app's conf file(such as httpd.conf) will goto /etc.

But from the view of source code, how do source code know the conf file is under /etc when parse it. I mean the code like fopen("/../../app.conf", "r"); is determined before we install it, will the configure file change source code or some other mechanism exist ?

like image 599
Linux-C-newbie Avatar asked Feb 20 '11 08:02

Linux-C-newbie


2 Answers

The configure script will generate the necessary Makefile that will use the C compiler's -DMACRO=content functionality to essentially inject C preprocessor #define MACRO content statements into the compilation units. So, sysconfdir could be used via Make rules:

foo.o: foo.c
        $(CC) -DCONFDIR=$(sysconfdir) -o $@ $<

(That says to build the foo.o object file when foo.c is updated; to build it, use the $(CC) variable to run the C compiler, define CONFDIR with the contents of $(sysconfdir) (supplied via the ./configure script), put output into the target file ($@) and give the source file ($<) as the lone input to the compiler.))

Then the C code in foo.c could use it like this:

 FILE *conf;
 if (conf = fopen(CONFDIR "/foo", "r")) {
     /* read config file */
 } else {
     /* unable to open config, either error and die or supply defaults */
 }

Note the C string concatenation is performed before compiling the program -- super convenient for exactly this kind of use.

More details here: http://www.gnu.org/software/hello/manual/autoconf/Installation-Directory-Variables.html#Installation-Directory-Variables

like image 164
sarnold Avatar answered Oct 11 '22 09:10

sarnold


When you execute ./configure, it typically generates a makefile that includes the command options for the C compiler. These options will include -D... options that (in effect) "#define" various CPP symbols. One of these will have the "/etc" value that you supplied when you ran ./configure --sysconfdir=/etc.

From there, the "/etc" string gets compiled into the code anywhere that the source code uses the #defined symbol.

like image 25
Stephen C Avatar answered Oct 11 '22 08:10

Stephen C