Logfile - How do I ...

From: Charles Sullivan (cwsulliv_at_triad.rr.com)
Date: 02/13/04


Date: Fri, 13 Feb 2004 17:02:12 GMT


I have this C code which can be executed in either a foreground or
background process, per user choice.

If executed in the foreground, the output should go to either stdout or
stderr (depending on the situation).

If executed in the background, all the output should go to a logfile, such
that the output will continue to be appended to the logfile even if at
some time the existing logfile is deleted (perhaps by the user or perhaps
by logrotate).

I thought at first I could do something like this:

  FILE *fdout, *fderr;

  int myfunct ( ... )
  {
     if ( background ) {
        fdout = fopen("myfile.log", "a");
        fderr = fdout;
     }
     else {
        fdout = stdout;
        fderr = stderr;
     }
     ...

     fprintf(fdout, ...);

     fclose(fdout);

     return 0;
  }

But then stdout gets closed also if the code is running in the foreground.

I suppose I could check again for background operation before fclose(),
but in the actual code things start to get messy as there are a large
number of return points.

Is there a neater way of accomplishing what I'm trying to do?

Thanks for your advice.

Regards,
Charles Sullivan