0

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! :)

2
  • Use a library or a script to do this sort of thing, no need to reinvent this wheel. Commented Oct 10, 2014 at 9:44
  • Just put a fprintf on stderr to discover where the child process exits. Commented Oct 10, 2014 at 9:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

scary story... what happens if you comment out everything related to fork (the call itself and the checks concerning pid variable)?
"Failed to create SID: -1" is output.
I guess we found the problem. Check errno for a more detailed description of the error. If you wait a second I will extend my answer to cover detailed error reporting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.