LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   No output to log file from daemon program (https://www.linuxquestions.org/questions/programming-9/no-output-to-log-file-from-daemon-program-869513/)

leonard_linuxquestions 03-18-2011 07:18 PM

No output to log file from daemon program
 
Hi, I am learning Linux daemon programming and write a simple daemon program. The issue is no data is written to the log file (/var/tmp/simpledeamon.log) though the file is successfully created (it's file size is zero from ls -l output). Could someone kindly point out the error in my program, Thanks.

The code is based on the Devin Watson's article at
http://www.netzmafia.de/skripten/uni...mon-howto.html. Here is the code:

// simplydaemon.cpp
// A simple Linux daemon.

#include <sys/types.h>
#include <sys/stat.h> // for umask
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
pid_t pid, sid; // child process id and session id.
FILE *fp_log;

// Fork off the parent process.
pid = fork();
if ( pid < 0 )
exit(EXIT_FAILURE);

// The child is born, kill the parent.
if ( pid > 0 )
exit(EXIT_SUCCESS);

// Now enter the child space.

// Change the file mode mask
umask(0);

// Open the log file.
if ( (fp_log = fopen("/var/tmp/simplydaemon.log", "a")) == NULL ) {
fprintf(stderr, "simplydaemon: fail to open log file.\n");
exit(EXIT_FAILURE);
}

// Create a new SID for the child
sid = setsid();
if ( sid < 0 ) {
fprintf(fp_log, "simplydaemon: fail to create a new SID for the child.\n");
fclose(fp_log);
exit(EXIT_FAILURE);
}

// Change the current working directory
if ( chdir("/") < 0 ) {
fprintf(fp_log, "simplydaemon: fail to change the current working directory");
fclose(fp_log);
exit(EXIT_FAILURE);
}

// Close all file descriptors
//for ( int i = getdtablesize(); i>=0; --i )
// close(i);
// Close the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

// The infinite loop
while (1) {
// The only work is to print some message to log file.
fprintf(fp_log, "simplydaemon: I am OK.\n");

// then sleep
sleep(60);
}

fclose(fp_log);
exit(EXIT_SUCCESS);
}

MS3FGX 03-18-2011 10:08 PM

Taking a quick look, I think the problem is simply that the file changes haven't been written to disk yet. It can take time for file writes to actually be committed to disk, and since this is only adding a very little amount to the file every minute, these operations could be cached in RAM for quite some time.

Closing the file should force the pending changes to get written out, but your logic prevents the program from ever closing the file (this is a bad idea in itself, by the way).

If you want to see this output in real time, use the fflush() function on the stream.

leonard_linuxquestions 03-19-2011 08:10 AM

MS3FGX, thanks. It works.


All times are GMT -5. The time now is 11:26 PM.