Daemon Process Deamon
is a background process that can be run without user input and used to provide a service in the background of the system.
Common daemons are WBE servers, mail servers, database servers, and so on. The daemon does not control the terminal, so any input and output needs to be handled in a special process.
The process of creating a daemon is not complex, first executing fork () and exiting the parent process.
A daemon is launched from a shell script or command, and the daemon and application are different in that the daemon is not interactive, it runs in the background and does not control the terminal.
The daemon does not need to read information from a standard input device, nor does it need to output information from a standard output device.
The next step is to call Setside () in the child process, canceling the association of the process and any control terminals.
The next step is to make the root directory the current working directory of the child process (optional) chdir ("/") ( if the working directory is set to the root directory, be aware that the path of the read pipeline is an absolute path and cannot write a relative path when you enter the command on the daemon through the channel implementation)
Because any process if its current directory is on an installed file system, it will prevent the file system from being uninstalled.
Next, execute umask (0), set the umask of the process to 0 to disconnect from the permissions on the inherited file, so that the program established by the daemon can be used normally by its users.
Finally, close any unnecessary file descriptors for the process. Close (Stdin_fileno); close (Stdout_fileno); close (Stderr_fileno);
Specifically close which depends on the needs and requirements of the daemon.
The related functions are:
Setsid () creates a new session and a fresh process group, and then the daemon becomes the session leader for the new session, and the process group leader for the newly created process group. The Setsid () call also guarantees that the new session has no control terminal
If the process that called the function is already a process group leader, the function call fails back to 1, and the errno is set, and success returns the Xinhui session ID.
The ChDir () function, int chadir (const char *pathname), returns 0 successfully, and the failure returns-1.
Umask () function, mode_t umask (mode_t mask);
To create the daemon code:
void Setdaemon () {pid_t pid, sid;pid = Fork (), if (PID < 0) {printf ("fork failed\n"); exit (exit_failure);} if (PID > 0) {exit (exit_success);//in the parent}if ((SID = Setsid ()) < 0) {printf ("Setsid failed\n"); Exit (Exit_ FAILURE);} if ((ChDir ("/")) < 0) {printf ("chdir failed\n"); exit (exit_failure);} Umask (0);//close (Stdin_fileno);//if close Stdin,then daemon_console failedclose (Stdout_fileno); Close (Stderr_fileno );}
once the system calls SETSID, it no longer has a control terminal. Services can be provided through the syslog to record various output information of the daemon
openlog function Open log, syslog write log, Closelog close the log.
The Openlog function initiates a connection to the Syslog server, and the parameters
Ident is the string to be added to each message, typical cases
is the name to set as the program.
? The parameter option is the "or" of one or more of the following values
name |
|
log_cons |
if Syslog server is not available, write to console |
log_ndelay |
Immediately open the connection, normally until the first message is sent |
log_perror |
print output to stderr |
log_pid |
Each message contains process pid |
The facitity parameter specifies the type of message that the program sends.
Name |
Meaning |
Log_authpriv |
Security Authorization Message |
Log_cron |
Clock daemon: cron and at |
Log_daemon |
Other System daemons |
Log_kern |
Kernel messages |
Log_lpr |
Printer Subsystem |
Log_mail |
Mail Subsystem |
Log_user |
Default |
The parameter priority specifies the importance of the message.
Name |
Meaning |
Log_emerg |
System cannot use |
Log_alert |
Take immediate Action |
Log_crit |
Emergency events |
Log_err |
Error condition |
Log_warning |
Warning conditions |
Log_notice |
Normal but significant event |
Log_info |
Informational messages |
Log_debug |
Debugging information |
Example of a syslog code:
Syslog (Log_info, "My daemin is OK");
Strictly speaking, Openlog and Closelog are optional, because the function syslog automatically opens the log file when it is first used. Log files on Linux systems are usually/var/log/messages
To communicate with a daemon, you want to send a signal to it to make it in some way appropriate. For example: forcing a daemon to reread its configuration file, or changing the daemon's behavior, or instructing the daemon to end its run.
Use the signal to communicate with the daemon. Adding a signal capture function to the daemon
void catch_signal (int sign ) { switch[sign] { case] c18> Sigterm:exit (exit_success); }}
end daemon through shell script.
#!/bin/Shwhoami=' WhoAmI ' PID'{print '}'if' $PID"") Thenkill $PIDfi
Note: The name of the script file does not have the word ' abc ', otherwise it will print out the script name when the PS is executed.
Use FIFO to communicate with daemons.
Read FIFO
voidReadfifo () {intLen =0; Charbuf[1024x768]; memset (BUF,0,sizeof(BUF)); intFD = open ("/home/test/1/fifo1", o_rdonly); while(len = Read (FD, BUF,sizeof(BUF)))>0) {printf ("%s\n", BUF); } close (FD); return;}
Write FIFO
voidWritefifo () {intLen =0; Charbuf[1024x768]; memset (BUF,0,sizeof(BUF)); intFD = open ("/home/test/1/fifo1", o_wronly); scanf ("%s", BUF); Write (FD, buf,sizeof(BUF)); Close (FD); return;}
How to get daemon programs running in the background to print to the screen Information.
daemon.c
1, execute mkfifo fifo1 command, create a pipe file named Fifo1.
2, compile the DAEMON.C, execute the program, close the terminal window of the current console, let the program run in the background.
3. Open a new terminal window, find the process PID via PS aux
4, execute kill–s 2 PID tty > fifo1
How to ensure that only one instance of a daemon is started.
#!/bin/Shwhoami=' WhoAmI ' PID'{print '}'if' $PID"") then. /ABCFI
Note: The name of the script file does not have the word ' abc ', otherwise it will print out the script name when the PS is executed.
Linux Creation Daemon