Reputation: 67
I have created a daemon for linux in c++, however, the child process does not seem to be doing anything. Once it reaches the if(pid > 0) statement, everything seems to stop. The code for the Daemon.Start() is as follows:
//Process ID and Session ID
pid_t pid,sid;
//Fork off the Parent Process
pid = fork();
if(pid < 0)
exit(EXIT_FAILURE);
//If PID is good, then exit the Parent Process
if(pid > 0)
exit(EXIT_SUCCESS);
//Change the file mode mask
umask(0);
//Create a new SID for the Child Process
sid = setsid();
if(sid < 0)
{
exit(EXIT_FAILURE);
}
//Change the current working directory
if((chdir("/")) < 0)
{
//Log the failure
exit(EXIT_FAILURE);
}
//Close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
//The main loop.
Globals::LogError("Service started.");
while(true)
{
//The Service task
Globals::LogError("Service working.");
if(!SystemConfiguration::IsFirstRun() && !SystemConfiguration::GetMediaUpdateReady())
{
SyncServer();
}
sleep(SystemConfiguration::GetServerConnectionFrequency()); //Wait 30 seconds
}
exit(EXIT_SUCCESS);
Any help would be great! :)
Upvotes: 0
Views: 504
Reputation: 1407
I'm pretty sure your child process dies within either the sid < 0
or the chdir("/") < 0
if statement. Write to stderr in these cases before exit to reveal what the problem is:
//Create a new SID for the Child Process
sid = setsid();
if(sid < 0)
{
fprintf(stderr,"Failed to create SID: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
//Change the current working directory
int chdir_rv = chdir("/");
if(chdir_rv < 0)
{
fprintf(stderr,"Failed to chdir: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
You need to include <errno.h>
and <string.h>
in order to have errno and strerror defined (respectively).
Regards
Upvotes: 1