The general server program is running in the background process (daemon), so how to make the server process daemon?
Here are the steps you follow to write the daemon:
1. Create a child process, close the parent process, 2. Sets the file permission mask. When a process creates a new file (using the open (const char *pathname, int flags, mode_t mode) system call, the file's permissions will be mode&0777;
3. Create a new session, set the process as the leader of the process group;
4. Switch the working directory;
5. Turn off standard input devices, standard output devices, and standard error output devices;
6. Close other file descriptors that are already open;
7. REDIRECT standard input, standard output, standard error to/dev/null file
Here is an example:
BOOLdaemonize () {pid_t PID=Fork (); if(PID <0 ) { return false; } Else if(PID >0) {exit (0 ); } umask (0 ); pid_t Sid=Setsid (); if(Sid <0 ) { return false; } if((ChDir ("/")) <0 ) { /*Log the failure*/ return false; } close (Stdin_fileno); Close (Stdout_fileno); Close (Stderr_fileno); Open ("/dev/null", o_rdonly); Open ("/dev/null", O_RDWR); Open ("/dev/null", O_RDWR); return true;}
In fact, Linux provides library functions that perform the same functions:
#include <unistd.h>int daemon (intint noclose);
Where the Nochdir parameter is used to determine whether to change the working directory, if Nochdir = 0, the working directory will be set to the root directory (/), otherwise continue to use the current working directory.
Noclose = 0 o'clock, standard input, standard output, standard error are redirected to the/dev/null file, otherwise the original device is still used.
Successful return 0, failure return-1
Server program daemon and the code of the daemon process