[Linux] Daemon and daemon threads

Source: Internet
Author: User
Tags syslog

For Java, typically one application has only one process--JVM. Unless a new process is derived or opened in the code.

threads, of course, are opened by the process. When the process that opened the thread leaves, the thread is no longer there.

So, for Java, threads are completely free to be generated by their own APIs. For example, New Thread (). But the process is different and must be done by invoking the OS API, such as Runtime.getRuntime.exec (). So, the process is the OS level concept.

The difference between a daemon thread and a user thread:

The two are basically the same. The only difference is when the JVM leaves.

User thread: The JVM will not leave when there is no user thread left.

Daemon Thread: If only the daemon thread is left, the JVM can leave.

In Java, it is very simple to make a daemon thread and take advantage of it directly . Setdaemon (True)

Many services are turned on in Linux or UNIX operating systems when the system is booted, and these services are called daemons. For added flexibility, root selects the system-enabled mode, which is called the RunLevel, and each runlevel configures the system in a certain way. Daemons are processes that are detached from the terminal and run in the background. The daemon is detached from the terminal to prevent the information in the process from being displayed on any terminal and the process will not be interrupted by terminal information generated by any terminal.

The daemon introduction daemon, which is usually called the daemon process, is the background service process in Linux. It is a long-lived process, usually independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons often start when the system boots, and terminate when the system shuts down. Linux systems have many daemons, most of which are implemented through daemons, while the daemon can accomplish many system tasks, such as the job planning process Crond, the printing process lqd, and so on (the end letter D is the daemon meaning).

Because in Linux, each system communicates with the user interface called the terminal, every process that starts from this terminal will be attached to this terminal, this terminal is called the control terminal of these processes, when the control terminal is closed, the corresponding process will automatically shut down. But the daemon is able to break through this limitation, and it will start running from execution until the entire system shuts down. If you want a process to not be affected by changes in the user or terminal or otherwise, you must turn the process into a daemon.

Creating DaemonsCreate child process, parent process exits

This is the first step in the process of writing the daemon. Since the daemon is out of control, the first step is to create the illusion that a program has finished running in the shell terminal. All subsequent work is done in the child process, and the user can execute other commands in the shell terminal to disengage from the control terminal in form.

In Linux, the parent process exits before the child process, causing the child process to become an orphan process, which is automatically adopted by the 1th process (init) when the system discovers an orphan process, so that the original child process becomes a child of the INIT process.

create a new session in a child process

This step is the most important step in creating the daemon, although its implementation is very simple, but its significance is very significant. The system function Setsid is used here, and before we introduce SETSID, we need to understand two concepts: Process group and session period

Process group: is a collection of one or more processes. The process group has a process group ID to uniquely identify. In addition to the process number (PID), the process group ID is also a prerequisite property for a process. Each process group has a leader process, and the process number of its leader process equals the process group ID. And the process group ID will not be affected by the exit of the leader process.

Session Period: The session period is a collection of one or more process groups. Typically, a session starts at the user logon and terminates when the user exits, during which all the processes that the user runs are part of the session period.

Next, you can specifically describe the SETSID content:

(1) Setsid function:

The SETSID function is used to create a new session and serve as the leader of the conversation group. Calling Setsid has the following 3 functions:

Let the process get rid of the control of the original session

Let the process get rid of the control of the original process group

Let the process get rid of control of the original control terminal

So why call the SETSID function when creating the daemon? Because the first step in creating the daemon calls the fork function to create the child process, and then exits the parent process. Because when the fork function is called, the child process copies the session period of the parent process, the process group, the control terminal, etc., although the parent process exits, but the session period, the process group, the control terminal and so on have not changed, so this is not the true sense of independence, and the SETSID function can make the process completely independent, So as to get rid of the control of other processes.

change the current directory to the root directory

This step is also a necessary step. A child process created with fork inherits the current working directory of the parent process. Because the file system in which the current directory resides (such as "/mnt/usb") is not unloaded while the process is running, this can cause a lot of trouble for later use (such as the system entering single-user mode for some reason). Therefore, the usual practice is to let "/" as the current working directory of the Daemon, so as to avoid the above problems, of course, if you have special needs, you can also change the current working directory to other paths, such as/tmp. A common functional chdir that changes the working directory.

Reset file Permission Mask

The file permission mask refers to the corresponding bit in the file permission that is masked out. For example, there is a file permission mask of 050, which masks the file group owner's readable and executable permissions. Because the new child process using the Fork function inherits the file permission mask of the parent process, this creates a lot of trouble for the child process to use the file. Therefore, setting the file permission mask to 0 can greatly enhance the daemon's flexibility. The function that sets the file permission mask is umask. Here, the usual method of use is Umask (0).

Close File Descriptor

As with the file permission code, a new child process with the fork function inherits some files that have already been opened from the parent process. These open files may never be read and written by the daemon, but they consume system resources as well, and may cause the file system in which they reside to fail to be unloaded.

After the second step above, the daemon has lost contact with the owning control terminal. As a result, characters entered from the terminal cannot reach the daemon, and characters that are output by a regular method (such as printf) in the daemon cannot be displayed on the terminal. Therefore, 3 files with file descriptors of 0, 1, and 2 (often referred to as input, output, and error) have lost their existing value and should be closed. The file descriptor is typically closed as follows:

===============================

for (i=0;i<maxfile;i++)

Close (i);

===============================

Daemon Exit processing

When the user needs an external stop daemon to run, the kill command is often used to stop the daemon. Therefore, in the daemon process, you need to

Encoding to achieve the signal signal processing of kill, to achieve the normal exit of the process.

===============================

Signal (SIGTERM, Sigterm_handler);

void Sigterm_handler (int arg)

{

_running = 0;

}

===============================

In this way, a simple daemon is set up.

Implement a full instance of the daemon (every 10s writes a word in/tmp/dameon.log):

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<fcntl.h>#include<sys/types.h>#include<unistd.h>#include<sys/wait.h>#include<signal.h>#defineMaxfile 65535volatilesig_atomic_t _running =1; intMain () {pid_t pc; intI,fd,len; Char*buf="This is a dameon\n"; Len=strlen (BUF); PC= Fork ();//The first step    if(pc<0) {printf ("Error fork\n"); Exit (1); }Else if(pc>0) Exit (0); Setsid (); //Step TwoChDir ("/");//Step threeUmask (0);//Fourth Step     for(i=0; i<maxfile;i++)//Fifth StepClose (i);  Signal (SIGTERM, Sigterm_handler);  while(_running) {if((Fd=open ("/tmp/dameon.log", o_creat| o_wronly| O_append,0600)) <0) {perror ("Open"); Exit (1);  } write (Fd,buf,len);  Close (FD); Usleep (Ten* +);//10 ms}}voidSigterm_handler (intArg) {_running=0; }
List of Linux daemons

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 governance process AutoMount, related to NFS, dependent on NIS

BOOTPARAMD: Boot parameter server for diskless workstations on LAN to provide information needed to boot

Scheduled Tasks under the Crond:linux

DHCPD: Start a DHCP (dynamic IP address Assignment) server

Gated: Gateway routing waiting process, using dynamic OSPF routing protocol

Httpd:web Server

INETD: A core waiting program that supports multiple network services

Innd:usenet News Server

Linuxconf: Promised to use the local Web server as the 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 scripted program that has a configured networking 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 governance, similar to inetd, which governs 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 promises 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 sharing/Printing service

SNMPD: Local Simple network governance 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 font server, providing font sets for local and remote X servers

XNTPD: Network time server

Ypbind: Activating Ypbind service process for NIS (Network Information System) client

Yppasswdd:nis Password Server

Ypserv:nis Primary Server

GPM: Tube-Mouse

Identd:auth services, similar to finger in the provision of user information

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.