1. Several points of understanding:
- There are two types of threads in Java: User thread, daemon thread (daemon)
- The daemon provides services for the running of other threads, such as GC threads (garbage collection threads), memory management threads.
- The virtual machine does not consider a daemon thread when it determines the standard of the execution of a program: If the user thread is all evacuated, daemon thread is out because there are no service objects.
- Public final void Setdaemon (Boolean on): User self-setting daemon thread
- is a mechanism defined by the JVM that simulates the "daemon" in the operating system. But it's different from the daemon process.
- You cannot set a running thread as a daemon: Thread.setdaemon (TRUE) must be set before Thread.Start () or a illegalthreadstateexception exception will run out. (Daemon is created, leave it out of Session + Process Group + Control Terminal Control)
- The thread created in daemon is also the daemon thread. (The process that the Daemon fork () is not a daemon because its parent process is no longer the INIT process)
- Not all applications can be assigned to the daemon service. such as read-write operations or computational logic, because the virtual machine has exited when daemon is not yet operational.
Example:
Public classDaemonthreadtest { Public Static voidMain (string[] args) {Thread T1=NewMyThread (); Thread T2=NewThread (NewMydaemon ()); T2.setdaemon (true); T1.start (); T2.start (); }}classMydaemonImplementsrunnable{ Public voidrun () { for(Longi=0; i<9999999l; i++) System.out.println ("Background line Cheng Di" + i + "time to execute!" "); Try{Thread.Sleep (7); }Catch(interruptedexception e) {e.printstacktrace (); } }}classMyThreadextendsthread{ Public voidrun () { for(inti=0; i<5; i++) System.out.println ("Line Cheng Di" + i + "time to execute!" "); Try{Thread.Sleep (7 ); }Catch(interruptedexception e) {e.printstacktrace (); } }}
Output:
The background thread executes for the NO. 0 time! The thread executes for the NO. 0 time! The background thread executes for the 1th time! The thread executes for the 1th time! The background thread executes for the 2nd time! The thread executes for the 2nd time! The background thread executes for the 3rd time! The thread executes for the 3rd time! The background thread executes for the 4th time! ... The background thread executes for the NO. 339 time!
That is, the foreground thread guarantees that execution is complete and the background thread does not.
2. Daemon Process
- Definition: in Linux or UNIX operating systems, many services are turned on during system boot, which is the daemon, the background service process . such as AMD (automatic installation of the NFS waiting process), LPD (print server), etc.
- Long lifetime. Typically, the system boot mount is started and terminates when the system shuts down.
- Independent of the control terminal and perform certain tasks periodically. Thus the information in the execution process is not displayed at the terminal and will not be interrupted by terminal process information.
- Terminal: In Linux, each system communicates with the user interface called the terminal (terminal), each process starting from the terminal will be attached to this terminal, which is known as the control terminal of these processes.
- When the control terminal is closed, the corresponding user process is automatically closed. The daemon can break this limit, that is, it will terminate when the system shuts down.
- When do I use daemons?
- If you do not want a process to be affected because of user/terminal/other changes, set the process as a daemon.
- To create a process:
- Creates a child process, and the parent process exits.
- That is, after the child process is created, the display exits the parent process, resulting in the illusion that the terminal process has finished running. Subsequent operations are completed by the child process. form and control Terminal detachment.
- Orphan process: The parent process exits before the child process, which is called the orphan process. After the system discovers an orphan process, it automatically has the 1th process (init process) adopted, which is called the child process of the INIT process.
- Creates a new session in a child process.
- Inheritance: Calls the fork () function, which copies all session periods, process groups, control terminals, etc. of the parent process. You need to reset these so that the child process is truly detached from the control terminal .
- Process group: One or more process collections. Each process has a process PID, and the process group has a group ID. Both the PID and the process group ID are required properties of a process. Each process group has a leader process whose process number equals the process group ID. When the process group ID is not affected by the leader process exit.
- Session period: One or more process group collections. Typically, a session starts with the user logging in and finally the user exits, and all processes between the sessions belong to that session period.
- Setsid: Creates a new session and serves as the leader of the conversation group. There are 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 conversation group
- Let the process get rid of control of the original control terminal
- Change the current directory to the root directory
- Inheritance: The child process created by fork () also copies the current working directory of the parent process. Need to reset.
- Process running, the current directory is located in the file system can not be uninstalled, that is, the original working directory cannot be uninstalled. Can cause a lot of hassle, such as needing to go into single-user mode. So the current directory must be reset.
- ChDir ("/"): Reset to root directory
- Reset File Permission Mask
- File permission mask: masks the corresponding bits in the file permissions. There is a file permission mask of 050, which masks the file group owner's readable and executable permissions.
- Inheritance: The child process created by fork () also inherits the file permission mask of the parent process.
- Umask (0): Reset to 0 for greater flexibility.
- Close File descriptor
- Inheritance: The child process created by fork () inherits some files that have already been opened from the parent process. A process that is opened may never be used by a daemon, but consumes resources. Therefore, you must manually close the file descriptor of 0, 1 and 2 of the 3 files (commonly said input, output and error).
- Daemon Exit Processing
- You may need to enable users to manually stop the daemon from running externally, typically by using the KILL command. The encoding implements the signal signal processing that the kill emits, reaching a normal exit of the thread.
Signal (SIGTERM, sigterm_handler); void Sigterm_handler (int arg) {_running = 0;}
Create an instance of the daemon:
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<fcntl.h>#include<sys/types.h>#include<unistd.h>#include<sys/wait.h>#defineMaxfile 65535voidSigterm_handler (intArg);volatilesig_atomic_t _running =1;intMain () {pid_t pc,pid;intI,fd,len,flag =1;Char*buf="This is a dameon\n"; Len=strlen (BUF);p c= Fork ();//The first stepif(pc<0) {printf ("Error fork\n"); exit (1);}Else if(pc>0) Exit (0);p ID= Setsid ();//Step two [1]if(PID <0) perror ("Setsid Error"); ChDir ("/");//Step threeUmask0);//Fourth Step for(i=0; i<maxfile;i++)//Fifth StepClose (i); signal (SIGTERM, sigterm_handler); while(_running) {if(Flag = =1&& (Fd=open ("/tmp/daemon.log", o_creat| o_wronly| O_append,0600)) <0) {perror ("Open"); flag=0; exit (1);} Write (Fd,buf,len); close (FD); Usleep (Ten* +);//10 ms}}voidSigterm_handler (intArg) {_running=0;}
Createdeamon
Daemon Thread, daemon