Brother Bird's Linux private cuisine 18th Chapter, Understanding System Services (Daemons)

Source: Internet
Author: User
Tags ftp file syslog system log ftp file transfer

what is daemon and services (service) Linux Daemon (daemon) is a special process running in the background. It is independent of the control terminal and periodically performs some sort of task or waits for certain events to be processed. It does not require user input to run and provide some kind of service, is not the whole system is to provide services to a user program. Most of the servers in a Linux system are implemented through a daemon process. Common daemons include the system log process syslogd, Web server httpd, mail server sendmail, and database server mysqld. The daemon generally starts running at system startup, unless it is forcibly terminated, until the system shuts down and remains running. Daemons often run with superuser (root) privileges because they want to use a special port (1-1024) or access certain special resources. The parent process of a daemon is the init process, because its true parent process exits the child process after it has been forked, so it is an orphan process inherited by Init. Daemons are non-interactive and do not have control terminals, so any output, whether it's stdout to a standard output device or a standard error device stderr, requires special handling. Working principleThe working mode of the Linux daemon is the server/client (server/client), the server listens on a specific port (Listen) waits for the client to connect, the server and the client communicate with the port after the connection is successful. The daemon's job is to open a port and listen (Listen) waiting for the client to connect. If the client generates a connection request, the daemon creates (Fork) a child server to respond to the connection, and the primary server continues to listen for other service requests.

Note: Linux can directly call the Damon function to implement the daemon process, there is no need to re-implement, understand its principle can be.

In Linux, a function is specifically provided to complete this daemon process, the prototype of this function is as follows

int int int __noclose);

If the value of __nochdir is 0, the working directory is switched to the root directory, and if __noclose is 0, the standard input, output, and standard errors are redirected to/dev/null.

After this function call the program will run in the background, become a daemon program, and Linux under the majority of services are running in this way.

Let's look at a simple example. For example, write an example program test.c

#include <unistd.h><stdio.h>int  do_sth () {    //Add what u Want     return0;} int Main () {    daemon (0,0);      while (1) {        do_sth ();        Sleep (1);}    }

Compile and run

gcc -o test test.c [[email protected] localhost daemon] $.

The program enters the background, through the PS view process situation, you can see the process's parent process ID is 1, that is, the INIT process

Root      3239  0.0  0.0   3920    ?        Ss   :   0:xx ./test

The so-called parent process is 1 of this expressed suspicion

Using lsof to view the files opened by the test process, you can see that the file descriptor 0,1,2 is redirected to/dev/null

Redirected to/dev/null also expressed doubts

And be able to see that the current working directory (CWD) of the process is the root directory/,daemon function has helped us to complete the process of daemon, and then we need to focus on the implementation of the program function.

main categories of daemon

According to Daemon's start-up and management mode can be divided into daemon can be independently launched stand alone, and through a super daemon to unify the management of two major categories:

    • Stand_alone: This daemon can start the service on its own

Stand alone is the meaning of "independent start". This type of daemon can be started on its own without having to be managed by other mechanisms, and it consumes memory and system resources after daemon is started and loaded into memory. The biggest advantage: because there is persistent in-memory service,stand alone's daemon responds faster to client requests. Common stand alone daemon have WWW daemon (httpd), FTP Daemon (VSFTPD), and so on.

    • Super Daemon: Unified Management by a special daemon

This type of service is initiated by a unified daemon that is responsible for invoking the service! This special daemon is called Super Daemon. The early Super Daemon was inetd and was later replaced by XINETD. When there is no client request, the services are not started, and when there is a request from the client, Super Daemon wakes the corresponding service. When the client's request is over, the service that is awakened also shuts down and frees the system resources.

The benefits of this mechanism are: (1) because Super Daemon is responsible for waking up services, Super Daemon can have a security control mechanism, similar to a network firewall! (2) Because the service is closed after the client's online end, it does not always occupy system resources. However, the service will be woken up because of the presence of the client, and the time that the service is loaded into memory needs to be taken into account, so the response time of the service will be slower! The common Super Daemon managed by the service has Telnet!

As shown above, Super daemon is resident in memory, program 1, 2, and 3 are programs that start some services (not started). When there is a client request, Super Daemon will trigger the relevant program to load into the daemon and exist in memory, at this time, the client's request will be Super Daemon Guide Daemon 1 to complete the service! When the client's request ends, Daemon 1 will be removed, and the online line in the diagram will be interrupted!

    • The Super daemon has two different processing modes, namely:

      • Multi-threaded (multithreading):

      • single-threaded (Single thread):

    • As shown above, the left side is multi-threaded operation, daemon will trigger a number of programs to provide services to different clients, so whether you are the first few requesters, you can enjoy the service of daemon. As for the right side is a single-threaded way, only one daemon is awakened, the first user to complete the service before the users of subsequent requests have to wait, so their online is not successful.
        • Types of daemon working patterns
        • Signal-control
          This daemon is managed through the signal, as long as any client requests come in, it will immediately start to deal with! For example, the printer's service (CUPSD).

        • Interval-control
          This daemon is mainly "to run a job every once in a while", so what you have to do is specify the time and work that the service will take in the configuration file, and the service will finish the work at the specified time. ATD and Crond belong to this type of daemon (detection of configuration files per minute)



        • Daemon's naming code

      Usually after the name of the service will be added a D, such as the creation of a routine command at, and Cron, the two services, his program file name will be taken as ATD and Crond, this d represents the meaning of daemon.

      Service-to-port correspondence

      All the functions of the system are provided by some programs, and the program is generated by triggering the program. Similarly, the network services provided by the system are of course the same!

      When the client comes over to our host, our host differentiates the service by port number

        • http://ftp.isu.edu.tw/
        • ftp://ftp.isu.edu.tw/

      Two URLs are the FTP sites that point to ftp.isu.edu.tw University, but the results shown on the browser are not the same! This is because we point to different services! One is HTTP this WWW service, and the other is the FTP file transfer service.


      Figure 1.2.1, port and daemon, the Client Connection protocol, service-oriented port number is also different

      In fact, in order to unify the whole Internet port number corresponding to the function of the service, so that all the host can use the same mechanism to provide service and demand services, so there is a "communication protocol" this thing. In other words, some of the conventional services are placed on the same port number! For example, the HTTP above the URL column will let the browser to the WWW server's 80 port number online requirements! The WWW server will also activate the HTTPD software at Port 80 so that both can be reached online!

      There is a configuration file on the system that provides the service and port:/etc/services!

[Email protected] ~]#Cat/etc/services .... (omitted earlier) ....FTP              +/TCPFTP              +/UDP FSP fspdSSH              A/TCP # SSH Remote Login ProtocolSSH              A/UDP # SSH Remote Login Protocol .... (omitted in the middle) .... http the/tcp www www-http # worldwideweb Httphttp the/udp www www-http # hypertext Transfer Protocol .... (omitted below) ....<daemon name> <port/Package Agreement > < description of the service >
Daemon startup script and startup mode

Provide a service daemon although only a program, but this daemon start or need to run the file, configuration files, running environment, etc., for example, you can look at the httpd this program (man httpd), which can talk about a lot of options and Parameters! In addition, in order to manage the above convenience, so usually distribution will record each daemon after the start of the program to obtain the PID in/var/run/this directory! Before you start these services, you may also want to handle the correct environment for daemon to run smoothly, and so on. Brother Bird here is to talk about, to start a daemon consider a lot of things, not simply run a program is enough.

In order to solve the problem mentioned above, usually distribution will give us a simple shell script to start the function. The script can be environment detection, configuration file analysis, PID file placement, as well as the relevant important Exchange file lock action, as long as you run the script, the above action is continuous, and finally can be smooth and simple to start the daemon!

So where are these daemon startup scripts (shell script)? Also, where does CentOS 5.x usually put daemon related files? And where are some important configuration files placed? Basically put it in these places:

  • /etc/init.d/*: Start Script placement
    Almost all service startup scripts on the system are placed here! In fact this is the accepted catalogue, our CentOS is actually placed in the/etc/rc.d/init.d/! However, there is still a configuration connection: to/etc/init.d/! Since this is a well-known directory, it is recommended that you remember this directory!

  • /etc/sysconfig/*: Initializing environment configuration file for each service
    Almost all services will write the initialization of some of the options configuration to this directory, for example, the login file syslog This daemon initialization configuration is written in/etc/sysconfig/syslog here! The configuration of the network is written in the/etc/sysconfig/network file. Therefore, the document in this directory is also very important;

  • /etc/xinetd.conf,/etc/xinetd.d/*: Super daemon config file
    Super Daemon's main profile (which is actually the default) is/etc/xinetd.conf, but as we mentioned above, Super Daemon is just a unified management mechanism, and other daemon configurations he manages are written in/etc/xinetd.d /* Inside Oh!

  • /etc/*: Individual configuration files for each service


  • /var/lib/*: Databases generated by each service
    Some services that generate data will write his data to the/var/lib/directory. For example, the database management system MySQL database default is to write/var/lib/mysql/this directory!

  • /var/run/*: PID records for each service program
    In the 17th chapter we talk about the use of signals (signal) to manage the program, since Daemon is a program, so of course you can use kill or killall to manage it! However, in order to worry about the management of other programs, so daemon will usually put their own PID record one to/var/run/! For example, the PID of the login file is recorded in the/var/run/syslogd.pid file. In this way,/etc/init.d/syslog can simply manage their own programs.

The section above is a configuration file, so how does the stand alone and Super Daemon manage the service startup mode? That's what he did:

    • Stand alone's/etc/init.d/* start

Just talked about almost all the services on the system startup scripts are under/etc/init.d/, the script will detect the environment, search configuration files, load distribution provided functions, determine whether the environment can run this daemon, etc. Wait until everything is detected and OK to run, then start, close, and observe this daemon with the CASE....ESAC syntax of the shell script! We can simply/etc/init.d/syslog this login to start the script to explain:

[Email protected] ~]#/etc/init.d/syslog usage:/etc/init.d/syslog {start|stop|status|restart|condrestart}# What parameters are not added, the system will tell you which parameters you can use, as shown above. Example one: Observe the current state of the syslog daemon [[email protected]~]#/etc/init.d/syslog statussyslogd (PID4264) running ... klogd (PID4267running ... # on behalf of Syslog Management Two daemon, these two daemon are running! Example two: Re-read the configuration file to syslog [email protected]~]#/etc/init.d/syslog Restart shutting down the core logger: [OK] shutting down the system logger: [OK] starting the system logger: [OK] starting the core logger: Determine [[Email protected]~]#/etc/init.d/syslog statussyslogd (PID4793) running ... klogd (PID4796is running ... # because of restarting, so the PID and the first observation of the value is not the same! How do you know that? 

Brother Bird's Linux private cuisine 18th Chapter, Understanding System Services (Daemons)

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.