"Network Programming" daemon

Source: Internet
Author: User
Tags openlog syslog terminates unix domain socket

Objective

Daemons are processes that run in the background and are independent of all terminal controls. Daemons do not have control of the terminal from which they are usually started by the system initialization script, but it is also possible to start from a terminal by typing the command line from a user at the shell prompt, which must be physically detached from the control terminal, thus avoiding job control, terminal session management, Any unintended interaction occurs when the terminal generates a signal, or the daemon running in the background is not expected to be output to the terminal. For job control, terminal control content can refer to the article "Operation Control, terminal control and Guardian process"

Because the daemon does not control the terminal, when the daemon fails, it must output an error message through some output function, rather than using the standard output function. The Syslog function is the standard way to output these messages, which send these messages to the SYSLOGD daemon.


SYSLOGD Daemon Process

The syslogd daemon in a Unix system is typically started by a system initialization script and runs continuously during system operation. The starting steps are as follows:

    1. Read the configuration file. Typically, the configuration file for/etc/syslog.conf specifies how the daemon handles different types of log messages. These log messages may be added to a file, or written to a specified user's login window, or forwarded to the SYSLOGD process on another host;
    2. Create a Unix domain datagram socket and bind it to the pathname/var/run/log (which may be/dev/log on some systems);
    3. Create a UDP socket to bind it to Port 514 (the port number used by the syslog service);
    4. Open path name/dev/klog. Any error message from the kernel is considered an input to this device;

Here's how the daemon generates log messages:

    1. The kernel routines can call the log function. Any user process can read these messages by opening (open) and then reading (read) the/dev/klog device;
    2. Most user processes (Daemons) invoke the Syslog function to generate log messages and send log messages to the Unix domain datagram socket/dev/log;
    3. One user process on this host, or one user process on another host connected to this host over a TCP/IP network, can send log messages to UDP port 514;




syslog function

Because the daemon does not control the terminal, error log messages cannot be fprintf to stderr, but syslog functions can be used to process log messages. It is defined as follows:

/* Daemon */#include <syslog.h>void syslog (int priority, const char *message, ...); void Openlog (const char *ident, int options, int facility), void closelog (void);/* Description: * functions Openlog and closelog are optional if openl is not called og function, the Openlog function is called automatically the first time the Syslog function is called, and the Openlog can be called before the first call to Syslog, Closelog can be called when the application process no longer needs to send the log message; The ident parameter is a string that precedes each log message by the syslog, usually the program name; * ****************************************************************** *    The options parameter consists of one or more logical "or" of the following values: * ****************************************************************** * (1) log_cons If it cannot be sent to the SYSLOGD daemon, the message is enlisted to the console * (2) Log_ndelay does not delay opening, creating the socket immediately * (3) Log_perror sent both to the syslogd daemon and to the standard error output * (4) Log_pid per Log messages are registered process ID * (5) log_nowait does not wait for a child process that may have been created during a message logging process * (6) Log_odelay delay opening the connection to the SYSLOGD daemon before logging the first message ******************* * Parameter priority is a combination of level and facility (facility); The purpose of level and facility is to allow all messages from the same given facility to be uniformly configured in the/dev/syslog.conf file, * or to uniformly configure all messages with the same levels; * ******************************* ********************* The level value is as follows: (note: The following priority from high to low) * ********************************************************* * Log_emerg system is not available * LO     G_alert must take immediate fix * log_crit critical condition * LOG_ERR error condition * log_warning warning Condition * Log_notice Normal however important condition (default) * Log_info Notification message * Log_debug Debug-level message *********************************************************** ******************************** * Facility values are as follows: * ********************************************************* * Log_auth Security /Authorization Message * LOG_AUTHPRIV Security/Authorization Message (private) * Log_cron CRON daemon * Log_daemon System daemon * log_ftp FTP daemon * Log_kern kernel generated Message * log_local0 reserved for local use * LOG_LOCAL1 reserved for local use * LOG_LOCAL2 reserved by local use * LOG_LOCAL3 reserved by local use * LOG_LOCAL4 reserved by local use * LO     G_LOCAL5 reserved by local use * LOG_LOCAL6 reserved by local use * LOG_LOCAL7 reserved by local use * LOG_LPR Line printer system * Log_mall mail system * log_news Network News System * Log_syslog messages generated internally by SYSLOGD * Log_user Any user-level messages (default) * LOG_UUCP UUCP System * ********************************* ************************ */ 

When the Syslog function is first called by the application process, it creates a UNIX domain datagram socket, and then calls the Connect function to connect to the pathname of the UNIX domain datagram socket created by the SYSLOGD daemon (for example,/var/run/log). The socket remains open until the process terminates.

When the Openlog function is called by an application, the Unix domain socket is usually not created immediately until the first call to the Syslog function is created and opened. However, the Openlog function can specify options log_ndelay require that the socket be created as soon as the Openlog function is called.


Daemon Process Programming

Daemon Process Programming Steps
1. Create child process, parent process exits
? All the work is done in the child process
? formally out of control terminal
2. Create a new session in a child process
? Setsid () function
? make child processes completely independent, out of control
3. Change the current directory to the root directory
? chdir () function
To prevent the use of unmounted file systems
? can also be replaced by other paths
4. Resetting the file permission mask
? Umask () function
Prevent inherited file creation masks from denying certain permissions
? Increased daemon Flexibility
5. Close the file descriptor
Inherited open files are not used, waste system resources, cannot be uninstalled
Returns the number of entries in the file descriptor for the process, that is, the number of files opened by the process


The process flow created by the daemon is as follows:




/* Initialize daemon */#include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <syslog.h># Include <fcntl.h> #include <signal.h> #include <sys/resource.h>extern void err_quit (const char *,...);    void daemonize (const char *pname, int facility) {int I, fd0, FD1, FD2;    pid_t pid;    struct Rlimit RL;    struct Sigaction sa;    Umask (0); /* Restrict process resources, parameter rlimit_nofile specifies that the process cannot exceed the maximum number of resources */if (Getrlimit (Rlimit_nofile, &AMP;RL) < 0) err_quit ("%s:can ' t get f    Ile limit ", pname);    /* Create Child process */if ((PID =fork ()) < 0) err_quit ("%s:can ' t fork", pname);    else if (pid! = 0) exit (0);/* Parent Process exits */setsid ();/* Create session */Sa.sa_handler = sig_ign;    Sigemptyset (&sa.sa_mask);    sa.sa_flags = 0;    if (Sigaction (SIGHUP, &sa, NULL) < 0) err_quit ("%s:can ' t ignore SIGHUP");    if (PID =fork ()) < 0) err_quit ("%s:can ' t fork", pname);    else if (pid! = 0) exit (0); /* Change the working directory to the root directory */if (ChDir ("/") < 0) err_quit ("%s:can ' t change directory to/");    if (Rl.rlim_max = = rlim_infinity) Rl.rlim_max = 1024;    /* Close all open descriptors */for (i = 0; i < (int) Rl.rlim_max; i++) Close (i);    fd0 = open ("/dev/null", O_RDWR);    FD1 = DUP (0);    FD2 = DUP (0);    /* Use SYSLOGD to process errors */Openlog (pname, log_cons, facility);        if (fd0! = 0 | | fd1! = 1 | | Fd2! = 2) {syslog (Log_err, "UNEXPECTRD file descriptors%d%d%d", fd0, Fd1, FD2);    Exit (1); }}

The specific steps of the daemon programming above are:

    1. First restrict the daemon's resources, then call Fork to create the child process, then terminate the parent process, leaving the child process to continue running. If this process is initiated from the foreground as a shell command, the Shell considers the command to be complete when the parent process terminates. This way, the process runs automatically in the background. In addition, the child process inherits the process group ID of the parent process, but the child process also has its own process ID, which guarantees that the child process is not the first process of a process group, so the SETSID function must be called to make the child process the first process of the process group;
    2. Call the Setsid function to create a new session. The current process becomes the session first process of the new session and the process group's first process, so there is no control terminal;
    3. Call the Sigaction function to ignore the SIGHUP signal, and call the fork function again, when the function returns, the parent process is actually the child process that the last Call fork produced, it is terminated, leaving the new child process to continue running. The purpose of calling fork again is to ensure that the daemon does not automatically get control terminals even when an end device is opened. When a session first process without a control terminal opens a device, the terminal automatically becomes the control terminal for this session's first process. However, after calling fork again, make sure that the new child process is no longer a session-first process, and therefore cannot automatically obtain a control terminal. When the session first process (that is, the child process that the first fork produces) terminates, all the processes in its session (that is, the sub-processes that are generated again) receive the SIGHUP signal, so the sigaction function must be called to ignore the signal;
    4. Change the working directory to the root directory. Because the daemon may start in an arbitrary file system, the file system cannot be disassembled without changing the working directory;
    5. Close all open descriptors of this daemon;
    6. Use SYSLOGD to handle errors;

inetd Daemon Process
Features of the inetd daemon:
    1. Simplify the process of preparing daemons;
    2. A single process can wait for external customer requests for multiple services;
The following is the workflow for the inetd daemon:


inetd Daemon Work steps:
    1. During the startup phase, read the/etc/inetd.conf file and create a socket of the appropriate type (byte stream or datagram) for each service specified in the file. Each newly created socket is added to a set of descriptors that will be used by a select call;
    2. Call the BIND function for each socket, specifying the port and the wildcard address of the appropriate server to bundle;
    3. For each TCP socket, call the Listen function to accept incoming connection requests;
    4. After all sockets are created, call the Select function to wait for any of the sockets to become readable;
    5. When select returns to indicate that a socket is readable, if the TCP socket and the server's Wait-flag value is nowait, then the accept accepts the new connection;
    6. The inetd daemon invokes the fork-derived process and processes the service request by the child process;
    7. The child process closes all descriptors except the socket descriptor to be processed;
The following functions are daemons that run by inetd and are simpler to program than the daemons above.
#include "unp.h" #include <syslog.h>extern intdaemon_proc;/* defined in error.c */voiddaemon_inetd (const char * pname, int facility) {Daemon_proc = 1;/* for our err_xxx () functions */openlog (PName, log_pid, facility);}



Reference: "Unix network Programming"

"Network Programming" 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.