"Network Programming" daemon

Source: Internet
Author: User
Tags openlog readable terminates

Objective

Daemons are independent of all processes in background execution and terminal control.

Daemon does not have a control terminal, because it is usually initiated by the system initialization script, however, it is possible to start by typing the command line from the user terminal Shell prompt. The process must be physically detached from the control terminal to avoid any unwanted interactions with job control, terminal session management, terminal generation signals, and so on. It is also possible to prevent daemons that are executing in the background from being output to the terminal in unexpected way. For job control, terminal control content can be included in the article "Operation Control, terminal control and daemon process"

Because the daemon does not control the terminal, when the daemon fails, you must output an error message through some output function. Instead of using standard output functions. 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 initiated by a system initialization script and is executed during system operation. The startup process is 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 is written to the login form of the specified user, or forwarded to a SYSLOGD process on a 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. 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 feels like the input of this device;

Here's how the daemon generates log messages:

    1. The kernel routines can call the log function. No matter what a 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 the log message to the Unix domain datagram socket/dev/log;
    3. A user process on this host. Or a user process on another host that is connected to this host over a TCP/IP network can send log messages to UDP Port 514.


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvy2hlbmhhbnpodw4=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


syslog function

Because the daemon does not control the terminal. Therefore, error log messages cannot be fprintf to stderr. However, you can use the Syslog function to process log messages.

Its definition is 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 you do not call the Openlog function, the first time you invoke the Syslog function. The Openlog function is invoked on its own initiative. * Openlog can be called before the first call to Syslog. Closelog can be called when the application process no longer needs to send log messages; * Ident is a string that precedes each log message by the syslog, typically the program name. * ****************************************************************** * options are composed of one or more logical "or" of the following denominations: * *************** * (1) If the log_cons 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 each log message is 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 levels and facilities (facility). * Level and facility are intended to agree to uniformly configure all messages from the same given facility in the/dev/syslog.conf file, * or uniformly configure all messages with the same levels. * ************************************************* The level value is as follows: (note: Below priority from high to low) * ********************************************************* * Log_emerg  System not Available * Log_alert must be immediately repaired * log_crit critical condition * LOG_ERR error condition * log_warning warning Condition * Log_notice Normal however important condition (default value) * LOG_INFO notification message * Log_debug Debug-level message *********************************************************** **********************  * Facility values such as the following: * ********************************************************* * 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 by local use * LOG_LOCAL2 reserved by local use * LOG_LOCAL3 reserved for local use * log_loc AL4 reserved by local use * LOG_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 by SYSLOGD * Log_user Discretionary 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 (such as/var/run/log).

The socket remains open until the process terminates.

When the Openlog function is called by the application. Unix domain sockets are not typically created immediately until the first time a syslog function is called, and the socket 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 work is done in the child process
? formally out of control terminal
2. Create a new session in a child process
? Setsid () function
? Make the child process completely independent, out of control
3. Change the current folder to the root folder
? 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
? Add Daemon Flexibility
5. Closing the file Description descriptor
Inherited open files are not used, waste system resources, cannot be uninstalled
Returns the number of entries in the file Description descriptor for the process. That is, the number of files opened by the process


The process flow created by the daemon is as follows:


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvy2hlbmhhbnpodw4=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


/* 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, 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 folder to the root folder */if (ChDir ("/") &LT    0) err_quit ("%s:can ' t change directory to/");    if (Rl.rlim_max = = rlim_infinity) Rl.rlim_max = 1024;    /* Close all open descriptive 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 detailed steps for programming the daemon 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 execution.

      If this process is initiated from the foreground as a shell command. When the parent process terminates, the shell feels that the command execution is complete. This way, the process executes itself 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. Therefore, 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 was generated by the last call to fork. It was terminated. Leave a new child process to continue execution.

      The purpose of calling fork again is to make sure that the daemon is in the future even when an end device is opened. Nor do they voluntarily acquire control terminals. When a session first process without a control terminal opens a device, the terminal itself becomes the control terminal of the session's first process.

      However, after calling fork again. Ensure that the new child process is no longer a session-first process, and therefore cannot proactively 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 subprocess that is generated again) receive the SIGHUP signal. Therefore, the Sigaction function must be called to ignore the signal;

    4. Change the working folder to the root folder. Because the daemon may be launched in a random file system, if the working folder is not changed, the file system will not be disassembled;
    5. Close the descriptive descriptor that the daemon has opened;
    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;
Here is the workflow for the inetd daemon:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvy2hlbmhhbnpodw4=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

inetd Daemon Work steps:

    1. The start phase. Read in 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 descriptive descriptors that will be used by a select call.
    2. Call the BIND function for each socket. Specifies the port and the wildcard address of the bundle's corresponding server.
    3. For each TCP socket, call the Listen function to accept incoming connection requests;
    4. After you create all the sockets, call the Select function to wait for whatever socket becomes 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, 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 descriptive descriptors except the socket descriptive descriptor to be processed;
The following function is a daemon-executed process performed by inetd, which is simpler to program than the daemon 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);}



References: Unix network programming

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

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