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.?