Zulakis
Zulakis

Reputation: 8384

fork writes filehandle again

My code looks somehow like this:

//INCLUDES

FILE *file;

void handlesocket(int socket);
int main(int argc, char *argv[])
{
    openlog("daemon", LOG_PID, LOG_USER);
    syslog(LOG_INFO, "daemon started.");
    file = fopen("/var/log/daemon.log","a+");
    fprintf(file,"Opened log file...");

     while (1) {
         pid = fork();
         if (pid == 0)  {
             handlesocket(socket);
             exit(0);
         }
         else close(socket);
     }
}

void handlesocket(int socket)
{
//handle socket
}

Basically, it is waiting for a new connections and then forks itself. (I removed all the socket code so it's easier to read.

My problem is that everytime a new connection comes in (and a new fork() is getting called) the fprintf seems to get called again and there is a new "Opened log file..." in my log.

Why does this happen?

Upvotes: 2

Views: 233

Answers (1)

Rafael Baptista
Rafael Baptista

Reputation: 11499

Fork duplicates the process completely - including the buffers used by fprintf. You need to flush the file handle right before the fork so that your forked process starts with io buffers clear:

fprintf( file, "opening log file\n" );
fflush( file );

Upvotes: 6

Related Questions