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);
}