APUE------Daemon

Source: Internet
Author: User
Tags openlog syslog

A daemon is a process that has a long lifetime. They often start when the system boots, and only terminate when the system shuts down. Because they do not have control terminals, they are running in the background.

Features of the daemon process

The system process relies on the operating system implementation. Processes with a parent process ID of 0 are typically kernel processes that are started as part of the system boot loader process. Kernel processes are special and usually exist throughout the life of the system. They run with superuser privileges, no control terminal, no command line.

Programming rules

There are some basic rules that need to be followed when writing daemon programs to prevent unnecessary interaction.
1. The first thing to do is to call Umask to set the file mode creation Shield Word to a known value. Creating a masked word from an inherited file pattern may be set to deny certain permissions. If the daemon is creating a file, it may want to set specific permissions.
2. Call fork, and then exit the parent process. Doing so achieves the following points. First, if the daemon is started as a simple shell command, then the parent process terminates to let the shell think that the command has been executed. Second, although the child process inherits the process group ID of the parent process, it obtains a new process ID, which guarantees that the child process is not a process group leader. This is a prerequisite for the SETSID call that will be made below.
3. Call a new session created by Setsid. Is the calling process: A. The first process known as a new session, B. The lead process, called a group of newly process, c. No control terminal
4. Change the current working directory to the root directory. The current working directory inherited from the parent process may be in a mounted file system. Because the daemon is always present before the system reboots, the file system cannot be uninstalled if the current working directory of the Daemon is in a mounted file system.
Or, some daemons may also change the current working directory to a specified location and do all of their work in this location.
5. Close the file descriptor that you no longer need. This causes the daemon to no longer hold any file descriptors inherited from its parent process. You can use the Open_max function or the Getrlimit function to determine the highest file descriptor value and close all descriptors until that value.
6. Some daemons open/dev/null so that they have file descriptors 0, 1, and 2, so any library routines that attempt to read standard input, write standard output, or standard error will have no effect. Because daemons are not associated with terminal devices, their output is nowhere to be displayed, and there is nowhere to accept input from interactive users. Even though the daemon is started from an interactive session, the daemon runs in the background, so the termination of the logon session does not affect the daemon. If other users log on on the same terminal, we do not want to see the output of the daemon on that terminal, and the user does not expect their input on the terminal to be read by the daemon.

Initialize a daemon

#include "apue.h"#include <syslog.h>#include <fcntl.h>#include <sys/resource.h>voidDaemonize (Const Char*cmd) {intI, Fd0, FD1, FD2; pid_t pid;structRlimit R1;structSigaction sa;/*clear file Creation mask*/Umask0);/*get Maximum number of file descriptors*/    if(Getrlimit (Rlimit_nofile, &AMP;R1) <0) Err_qiut ("%s:can ' t get file Limit", CMD);/*become A session leader to lose controlling tty*/    if(PID = fork ()) <0) Err_qiut ("%s:can ' t fork", CMD);Else if(PID! =0)Exit(0); Setsid ();/*ensure Future opens won ' t allocate controlling ttys*/Sa.sa_handler = sig_ign; Sigemptyset (&sa.sa_mask);if(Sigaction (SIGHUP, &sa, NULL) <0) Err_quit ("%s:can ' t ignore SIGHUP", CMD);if(PID = fork ()) <0) Err_quit ("%s:can ' t fork", CMD);Else if(PID! =0)Exit(0);/*change The working directory to the root so *wo won ' t prevent file systems from being unmounted */    if(ChDir ("/") <0) Err_quit ("%s:can ' t directory to/", CMD);/*close all open file descriptors*/    if(R1.rlim_max = = rlim_infinity) R1.rlim_max =1024x768; for(i =0; I < R1.rlim_max; i++) Close (i);/*attach file descriptors 0,1 and 2 to/dev/null*/fd0 = open ("/dev/null", O_RDWR); FD1 = DUP (0); FD2 = DUP (0);/*initialize the log file*/Openlog (cmd, log_cons, Log_daemon);if(Fd0! =0| Fd1! =1| Fd2! =2) {syslog (Log_err,"Unexpected file descriptors%d %d%d", Fd0, FD1, FD2);Exit(1); }}
Error logging

One problem with the daemon is how to handle the error message because it should not have a control terminal, so it cannot simply be written to the standard error.

There are 3 ways to generate log messages.
1. Kernel routines can call the log function. Any user process can read this information by opening and reading the/dev/klog device.
2. Most user processes (Daemons) invoke the Syslog (3) function to generate log messages. This causes the message to be sent to the UNIX domain datagram socket/dev/log.
3. Log messages can be sent to UDP port 514 regardless of whether a user process is on this host or on another host that is connected to this host over a TCP/IP network. Note that syslog functions never produce these UDP datagrams, which require the network programming of the process that produces this log message to be displayed.

Typically, the syslogd daemon reads day messages in all 3 formats. This daemon reads a configuration file at startup, whose file name is typically/etc/syslog.conf, which determines where different kinds of messages should be sent. For example, an emergency message can be sent to the system administrator and printed on the console, while a warning message can be recorded in a file.

#include  <syslog.h>void openlog(constcharintint facility);void syslog(intconstchar *format, ...);void closelog(void);int setlogmask(int maskpri);//返回值:前日志记录优先级屏蔽字值

The call to Openlog is selectable. If you do not call Openlog, the Openlog is called automatically when you first call the syslog. Calling Closelog is also a lesson choice because it is just a descriptor that the shutdown layer is used to communicate with the SYSLOGD daemon.

Calling Openlog allows us to specify a ident, in which case the ident will be added to each log message. Ident is generally the name of the program. The option parameter is a bit mask that specifies various options.

option Description
Log_cons Writes the message to the console if the log message cannot be submitted to syslogd through UNIX domain data
Log_ndelay Open the UNIX domain datagram socket immediately to the SYSLOGD daemon, and do not wait until the first message has been recorded. Typically, the socket is not opened until the first message is recorded
Log_nowait Do not wait for child processes that may have been created during the logging of messages.
Log_odelay Delay opening the connection to the SYSLOGD daemon before the first message is recorded
Log_perror In addition to sending a log message to SYSLOGD, it is also written to standard error
Log_pid Record each message to include the process ID. This option is used by the daemon for each of the different requests that fork a child process.

The facility parameter values for Openlog are selected from the following

facility Description
Log_audit Audit facilities
Log_auth Authorization procedure: Login, Su, Getty, etc.
Log_ Authpriv Same as Log_auth, but with permission restrictions when writing log files
Log_console Message Write/dev/console
Log_cron Cron and at
Log_daemon System daemon: inetd, routed, etc.
Log_ftp FTP Daemon
Log_kern Message generated by the kernel
Log_local0~7 Reserved by local use
Log_lpr Line Printer system: LPD, LPC, etc.
Log_mail Mail system
Log_news Usenet Network News system
Log_ NTP Network Time Protocol System
Log_security Security subsystem
Log_syslog STSLOGD Daemon Process itself
Log_user Messages from other user processes
Log_uucp UUCP system

The purpose of setting the facility parameter is to let the configuration file indicate that messages from different facilities will be processed in different ways. If you do not call Openlog, or call it as facility, you can describe facility as part of the priority parameter when you call the syslog.

Invoking a syslog generates a log message. The priority parameter is a combination of facility and level

Level
Description
Log_emerg Emergency
Log_alert Situations that must be repaired immediately
Log_crit Serious situation
Log_err Error condition
Log_warning Warning conditions
Log_notice A normal but important situation
Log_info Informational messages
Log_debug Debug messages

Pass the format parameter and all other parameters to the vsprintf function for formatting. In format, each occurrence of the%m character is replaced with an error message string corresponding to the errno value.

The Srtlogmask function is used to set the record priority screen word for a process.

Single Instance Daemon

Ensure that only one copy of the daemon is running

#include <unistd.h>#include <stdlib.h>#include <fcntl.h>#include <syslog.h>#include <string.h>#include <errno.h>#include <stdio.h>#include <sys/stat.h>#define LOCKFILE "/var/run/daemon.pid"#define Lockmode (s_irusr | S_IWUSR | S_irgrp | S_iroth)extern intLockfileint);intAlready_running (void){intFd FD = open (LOCKFILE, O_RDWR |0_creat, Lockmode);if(fd <0) {syslog (Log_err,"can ' t open%s:%s", LOCKFILE, Strerror (errno));Exit(1); }if(Lockfile (FD) <0){if(errno = = Eacces | | errno = = eagain) {Close (FD);return(1); } syslog (Log_err,"can ' t lock%s:%s", LOCKFILE, Strerror (errno));Exit(1); } ftruncate (FD,0); Sprint (BUF,"%ld", (Long) getpid ()); Write (FD, buf,strlen(BUF) +1);return 0;}
The Convention of the Daemon process
    1. If the daemon uses a lock file, the file is usually stored in the/var/run directory. However, it is important to note that the daemon may need to have superuser privileges to create files in this directory. The name of the lock file is usually name.pid, where name is the name of the daemon or service.
    2. If the daemon supports configuration options, the configuration file is usually stored in the/etc directory. The name of the configuration file is usually name.conf, where name is the name of the daemon or service.
    3. Daemons can be started with the command line, but usually they are initiated by one of the system initialization scripts.
    4. If a daemon has a configuration file, it will be read when the daemon is started, but it will not be viewed again after this process. If an administrator changes the configuration file, the daemon may need to be stopped before it can be started for the configuration file to take effect. To avoid this kind of trouble, some daemons will capture the sighup signal and reread the configuration file when they receive the signal.

Daemon Reread configuration file

#include "apue.h"#include <pthread.h>#include <syslog.h>sigset_t Mask;extern intAlready_running (void);voidReread (void){/*...*/}voidTHR_FN (void*arg) {intArr,signo; for( ; ; ) {err = sigwait (&mask, &signo);if(Err! =0) {syslog (Log_err,"Sigwait failed");Exit(1); }Switch(Signo) { CaseSighup:syslog (Log_info,"re-reading configuration File"); Reread (); Break; CaseSigterm:syslog (Log_info,"Got SIGTERM; Exiting ");Exit(0);default: Syslog (Log_info,"Unexpected signal%d\n", Signo); }       }return 0;}intMainintargcCharArgv[]) {intErr pthread_t Tid;Char*cmd;structSigaction sa;if(cmd =STRRCHR(argv[0],'/')) = = NULL) cmd = argv[0];Elsecmd++;/*become a daemon*/Daemonize (CMD);/*make sure only one copy of the daemon is running*/    if(Already_running ()) {Syslog (Log_err,"Daemon already Running");Exit(1); }/*restore SIGHUP Default and block all signals*/Sa.sa_handler = SIG_DFL;    Sigemptyset (&sa.sa_mask); Sa.sa_flags =0;if(Sigaction (SIGHUP, &sa, NULL) <0) Err_quit ("%s:can ' t restore SIGHUP default"); Sigfillset (&mask);if(Err = Pthread_sigmask (Sig_block, &mask, NULL))! =0) Err_exit (Err,"Sig_block Error");/*create a thread to handle SIGHUP and sigterm*/Err = Pthread_create (&tid, NULL, THR_FN,0);if(Err! =0) Err_exit (Err,"can ' t create thread");/*proceed with the rest of the daemon*/    /* ... */    Exit(0);}
Client process-Server process model

The daemon tasted as a server process.
In general, the server process waits for the client process to contact it and proposes some kind of service requirement. The service provided by the SYSLOGD server process logs an error message to the log file.
It is common to call fork in the server process and then exec another program to serve the client process. These server processes typically manage multiple file descriptors: Communication endpoints, configuration files, log files, and similar files. In the best case, it is no big deal to keep these file descriptors open in a child process, as they will most likely not be used by programs that are executing in a child process, especially those that are not related to the server side. In the worst case, keeping them open can lead to security issues-the executed program may have some malicious behavior, such as changing the server-side configuration file or tricking the client program into thinking it is communicating with the server side to obtain unauthorized information.
An easy way to resolve this problem is to turn off the flag when execution is performed on all file descriptor settings that are not required by the executing program

APUE------Daemon

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.