I am trying to figure out how to make my program a demon. So some of the things that I came across, in general, the program performs the following steps to become a demon:
- Call
fork( ) . In the parent, call exit( ) . This ensures that the original parent (the demon grandparents) is satisfied that his child has stopped, that the demon parent is not and that the demon is not the leader of the process group. This last point is a prerequisite for the successful completion of the next step.
Call setsid( ) , providing the daemon with a new process group and session, both of which have it as a leader. It also ensures that the process is not connected (because the process has just created a new session and will not assign one).
Change the working directory to the root directory using chdir( ) . This is because the legacy working directory can be located anywhere in the file system. Daemons tend to work throughout the entire system, and you do not want to open any random directory and thus prevent the administrator from unmounting the file system containing this directory.
Close all file descriptors.
- Open the file descriptors 0, 1, and 2 (standard, standard, and standard error) and redirect them to
/dev/null .
#include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <linux/fs.h> int main (void) { pid_t pid; int i; /* create new process */ pid = fork ( ); if (pid == -1) return -1; else if (pid != 0) exit (EXIT_SUCCESS); /* create new session and process group */ if (setsid ( ) == -1) return -1; /* set the working directory to the root directory */ if (chdir ("/") == -1) return -1; /* close all open files--NR_OPEN is overkill, but works */ for (i = 0; i < NR_OPEN; i++) close (i); /* redirect fd 0,1,2 to /dev/null */ open ("/dev/null", O_RDWR); /* stdin */ dup (0); /* stdout */ dup (0); /* stderror */ /* do its daemon thing... */ return 0; }
Can someone give me a link to the existing source code of some program such as Apache so that I can understand this process in more detail.
c linux systems-programming daemon
Registered User Mar 21 2018-11-21T00: 00Z
source share