Introduction to the Linux daemon and detailed examples

Source: Internet
Author: User
Tags syslog

Introduction to the Linux daemon and detailed examples

Introduction

A daemon (Daemon) is a special process that runs in the background. It is independent of the control terminal and periodically performs certain tasks or waits for certain occurrences to be handled. The daemon is a useful process. Most Linux servers are implemented with daemons. For example, The Internet server Inetd,web server httpd and so on. At the same time, the daemon completes many system tasks. For example, the job planning process Crond, the print process LPD, and so on.

The following are some of the daemons that are common in Linux systems.

AMD: Automatic installation of NFS (Network file system) daemon
APMD: Advanced Power Management
Arpwatch:Log and build an Ethernet address and IP address to the database that you see on the LAN interface
Autofs:Automatic installation of the management process AutoMount, related to NFS, dependent on NIS
Bootparamd:Boot parameter server to provide information needed to boot the diskless workstation on the LAN
Crond:Scheduled Tasks under Linux
Dhcpd:Start a DHCP (dynamic IP address Assignment) server
Gated:Gateway routing waiting process, using dynamic OSPF routing protocol
Httpd:Web server
Inetd:Core waiting programs that support multiple network services
Innd:Usenet news server
Linuxconf:Allows the use of a local Web server as a user interface to configure the machine
Lpd:Print server
Mars-nwe:Mars-nwe files and print servers for Novell
Mcserv:midnight Command File Server
Named:dns Server
NETFS: Installing NFS, Samba, and NetWare network file systems
Network:Activating a script that has a configured network interface
Nfs:Open NFS Service
Nscd:NSCD (Name Switch cache daemon) server, a support service for NIS that caches user passwords and constituent memberships
Portmap:RPC Portmap Manager, similar to inetd, which manages RPC service-based connections
PostgreSQL:A SQL database server
Routed:Routing waiting process, using dynamic RIP routing protocol
Rstatd:A waiting program that collects and provides system information for other machines on the LAN
Ruserd:Remote User location service, which is an RPC-based service that provides user information about the current record to a machine log in the LAN
Rwalld:Activates the Rpc.rwall service process, an RPC-based service that allows users to write messages to each other terminal registered on the LAN machine
Rwhod:Activates the Rwhod service process, which supports LAN rwho and Ruptime services
SendMail:Mail server SendMail
Smb:Samba File share/Print Service
Snmpd:Local Simple network management waiting process
Squid:Activating the proxy server squid
Syslog:A script that lets the system boot up syslog and klogd the system log waiting process
Xfs:X Window-shaped server that provides font sets for local and remote x servers
Xntpd:Network time server
Ypbind:Activating the Ypbind service process for NIS (Network Information System) clients
Yppasswdd:nis Password Server
Ypserv:nis Primary Server
GPM: Managing Mouse
Identd:Auth services, similar to finger in the provision of user information

Programming Essentials for Daemons

The daemon programming itself is not complex, the complexity of the various versions of UNIX implementation mechanism is not the same, resulting in different UNIX environment daemon programming rules are not consistent. The following describes the programming essentials of the Linux daemon and gives a detailed example.

The programming rules for daemons in different UNIX environments are inconsistent. Fortunately, the Daemon programming principles are all the same, the difference is that the specific implementation details are different. This principle is to satisfy the nature of the daemon. Programming essentials are as follows:

  1. Run in the background. To avoid suspending the control terminal, daemon is placed in the background. The method is to call fork in the process to terminate the parent process and let Daemon execute in the child process.
  2. Out of control terminal, logon session and process group. It is necessary to introduce the relationship between the process and the control terminal in Linux, the logon session and the process group: the process belongs to a process group, and the process group number (GID) is the process number (PID) of the process leader. A logon session can contain more than one process group. These process groups share a control terminal. This control terminal is usually the login terminal to create the process. Control terminals, logon sessions, and process groups are usually inherited from the parent process. Our aim is to get rid of them so that they are not affected by them. The method is based on the 1th, Call Setsid () to make the process a conversation leader. (Description: The Setsid () call failed when the process was the session leader. But the 1th has ensured that the process is not a conversation leader.) After the Setsid () call succeeds, the process becomes the new session leader and the new process leader and is detached from the original logon session and process group. Due to the exclusivity of the session process to the control terminal, the process is detached from the control terminal at the same time.
  3. Prevents the process from reopening the control terminal. Now, the process has become a session leader without terminal. But it can reapply to open a control terminal. You can prevent a process from reopening the control terminal by making the process no longer a session leader.
  4. Closes the open file descriptor. The process inherits the open file descriptor from the parent process that created it. If you do not close, you will waste system resources, causing the file system where the process resides to fail to unload and cause unexpected errors.
  5. Changes the current working directory. The file system in which the working directory resides cannot be unloaded when the process activity is active. The working directory is typically changed to the root directory. For the process that needs to dump the core, write the log to change the working directory to a specific directory such as/tmpchdir ("/").
  6. Resets the file creation mask. The process inherits the file creation mask from the parent process that created it. It may modify the access bit of the file created by the daemon. To prevent this, the file creation mask is cleared: umask (0).
  7. Process the SIGCHLD signal. It is not necessary to process the SIGCHLD signal. However, for some processes, especially server processes, it is often possible to generate child process processing requests when a request arrives. If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) Thus occupying system resources. If the parent process waits for the child process to end, it increases the burden on the parent process and affects the concurrency performance of the server process. Under Linux, you can simply set the operation of the SIGCHLD signal to sig_ign. This way, the kernel does not spawn a zombie process at the end of the child process.

Daemon Process InstanceThe daemon instance consists of two parts: the main program TEST.C and the initialization program INIT.C. The main program reports the running state to the log test.log in the/tmp directory every other minute. The Init_daemon function in the initializer is responsible for generating the daemon. Readers can take advantage of the Init_ The daemon function generates its own daemon.
1.INIT.C List
#include < unistd.h > #include < signal.h > #include < sys/param.h > #include < sys/types.h > #inc Lude < sys/stat.h > void Init_daemon (void)  {  int pid;  int i;  if (Pid=fork ())  exit (0);//is parent process, end parent process  else if (pid< 0)  exit (1),//fork failed, exit  //Is first child process, background continues execution  Setsid ();//The first child process becomes the new session leader and the process leader, and separates the  if (Pid=fork ()) exit from the control terminal  (0);//is the first subprocess, ending the first child process  else if (pid< 0)  exit (1);//fork failed, exit  //is the second child process, continue, second child process is no longer a session leader  for (i=0;i< nofile;++i)//Close Open File descriptor  Close (i );   ChDir ("/tmp");//Change Working directory to/TMP  umask (0);//reset file Create mask  return;  
2.TEST.C List
#include < stdio.h > #include < time.h >   extern void Init_daemon (void);//daemon initialization function   main ()   {    FILE *FP;     time_t T;     Init_daemon ();//Initialize     to Daemon while (1)//Every minute to Test.log report the running state     {       sleep (60);//Sleep One minute       if (Fp=fopen (" Test.log "," a ")) (>=0)       {         t=time (0);         fprintf (FP, "I m here at%s\n", Asctime (LocalTime (&t)));        Fclose (FP);       }    }  

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.