0

I have a server program written in c++, that manages the traffic between the user's browser and a hardware device. This server runs on my centos machine. When I run the program normally it runs without any problem.

But trying to run the program as a daemon brings up some problems. This is my code for the daemon:

pid_t pid, sid;

pid = fork();
if(pid < 0){
    exit(EXIT_FAILURE);
}

if(pid > 0) {
    exit(EXIT_SUCCESS);
}

umask(0);

sid = setsid();
if(sid < 0){
    exit(EXIT_FAILURE);
}

if((chdir("/")) < 0){
    exit(EXIT_FAILURE);
}

close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

while(1){
   //my program here
}

The program starts fine, it's parent is init. It can run for hours, but when I make about 10 - 15 requests, it stops.

I believe the code for running my program as a deamon is correct. What I am worried about is my actual code. Are there any rules I have to follow? Any bad behaviour I should avoid? Any commands that are not allowed with a daemon, like command line output(which I make a lot at the moment), etc.?

megadave
  • 100
  • 10
  • 2
    http://stackoverflow.com/questions/3095566/linux-daemonize I think you have to close or redirect your stdout and stderr, or not write to them at all. Or use daemonize or any of the other tools to run your "normal" program as a daemon. – Prof. Falken Aug 22 '13 at 06:26
  • Removing all the output did the trick. Now everything is working fine. – megadave Aug 23 '13 at 10:55

1 Answers1

0

Simply closing stdout and stderr will make all writes to these fail. I guess your program runs into such an error, detects it and terminates. The standard technique is to open /dev/null and dup2(2) it to STDOUT_FILENO, STDERR_FILENO and STDIN_FILENO.

user2719058
  • 2,183
  • 11
  • 13