What is a daemon process The Q daemon is a process running in the background that is not controlled by the control, and normally the daemon runs automatically at system startup The name of the Q daemon usually ends with D, such as sshd, xinetd, Crond, etc. |
To create a daemon step Q Call Fork (), create a new process, it will be the future daemon Q Call exit in the parent process to ensure that the child process is not the process group leader Q Call Setsid to create a new session period Q Change the current directory to the root directory (if the current directory is the directory of the daemon, the current directory cannot be uninstalled, it is the working directory of the Daemon.) ) Q REDIRECT standard input, standard output, standard error to/dev/null |
Daemon API int daemon (int nochdir, int noclose); Q function: Create a daemon Q parameter: Q nochdir:=0 Change the current directory to "/" Q noclose:=0 REDIRECT standard input, standard output, standard error to "/dev/null" |
Mans Setsid
DESCRIPTION
Setsid () creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and have no contr Olling TTY. The process group ID and session ID of the The calling process is set to the PID of the calling process. The calling process is the only process in this new process group and the new session.
Some processes have TTY, and some processes do not have TTY. The guard process is the one with the question mark.
Session period: is a collection of one or more process groups, typically a session period begins with the user's logon and terminates when the user exits. During this time, all processes run by the user belong to this session period.
#include <unistd.h>#include<sys/stat.h>#include<sys/wait.h>#include<sys/types.h>#include<fcntl.h>#include<stdlib.h>#include<stdio.h>#include<errno.h>#include<string.h>#include<signal.h>#defineErr_exit (M) Do{perror (M); Exit (Exit_failure); } while(0)intSetup_daemon (intNochdir,intnoclose);intMainintargcChar*argv[]) {Mydaemon (1,1); //Man Daemon can see//0 means change redirect 1 means no change//Daemon (1, 1);printf"test ... \ n"); for (;;) ; return 0;}intMydaemon (intNochdir,intnoclose) {pid_t pid; PID=Fork (); if(PID = =-1) Err_exit ("Fork Error"); if(PID >0) exit (exit_success); Setsid (); if(Nochdir = =0) ChDir ("/"); if(Noclose = =0) { inti; for(i=0; i<3; ++i) close (i); Open ("/dev/null", O_RDWR);//Associate the daemon's standard output to the process's No. 0 FD file Descriptor//Copy the 0 file descriptor to a free file descriptorDup0);//standard output also points to/dev/null//dup2 (0, 1);DUP (0);//standard error output, also pointing to/dev/null//dup2 (0, 2); } return 0; }
Pictures from beloved teacher: Wang Paoming
Copy to Google TranslateTranslation Results
[Learning notes] Daemon Insights