Implementation of the Python daemon

Source: Internet
Author: User
Tags save file

Daemon scene

Consider the following scenario: You write a Python service program and start at the command line, and your command lines are controlled by the terminal, and the Python service becomes a subprocess of the terminal program. So if you close the terminal, the command-line program will also close.

To keep your Python service from being affected by the terminal system, you need to turn it into a daemon.

A daemon is a daemon program, a program that executes in the background of a system that is independent of the control terminal and performs some periodic tasks or triggering events, usually named "D" to end, such as Common httpd, SYSLOGD, Systemd, and Dockerd.

Code implementation

Python can implement the daemon very concisely, with the code and the corresponding comments given below. This code runs stably in a daemon (homemade alarm clock) on my local computer, and has not had a problem for the time being.

# coding=utf8import Osimport sysimport atexitdef daemonize (pid_file=none): "" "Create Daemon:p Aram Pid_file: Save file for process ID : "" "# Fork a child process from parent process out PID = Os.fork () # The PID of the subprocess must be 0, the parent process is greater than 0 if PID: # exits the parent process, the Sys.exit () method is more than The Os._exit () method performs some more refresh buffering work sys.exit (0) # child processes inherit the working directory of the parent process by default, preferably to the root directory, or back to the file system's uninstall Os.chdir ('/') # Child processes inherit the parent process by default U Mask (file permission mask), reset to 0 (Full Control), so as not to affect the program read and write files Os.umask (0) # Let the child process become a new session leader and process leader Os.setsid () # Note that this is the 2nd time Fork, which is the child process of the subprocess, we put It's called for grandson process _pid = Os.fork () If _pid: # exit Subprocess sys.exit (0) # At this point, the grandson process is already the daemon, then redirect the standard input, output, and error descriptors (redirection without is off, which prevents the program from making an error in print) # Flush buffer First, be careful to make the perpetual ship Sys.stdout.flush () Sys.stderr.flush () # dup2 function atomically Close and copy the file descriptor, redirecting to /dev/nul, which discards all input outputs with open ('/dev/null ') as Read_null, open ('/dev/null ', ' W ') as Write_null:os.dup2 (Read_null.  Fileno (), Sys.stdin.fileno ()) os.dup2 (Write_null.fileno (), Sys.stdout.fileno ()) os.dup2 (Write_null.fileno (),   Sys.stderr.fileno ()) # write PID file if Pid_file:with open (pid_file, ' w+ ') as F:f.write (str (os.getpid ())) # Register Exit Function, Process XOR Remove PID file Atexit.register (Os.remove, pid_file) when exiting

Summarize the steps to write the daemon:

1, fork out the child process, quit the parent process

2. Child process Change Working directory (chdir), file permission mask (umask), process group, and session group (SETSID)

3, sub-process fork grandson Process, exit child process

4, grandson process Refresh buffer, redirect standard input/output/error (General to/dev/null, meaning discard)

5. (optional) PID write file

Understand a few points

Why Fork two times

The first fork is to disengage from the claws of the terminal control. The parent process exits because it sends a signal when the terminal strikes the keyboard, or when it is closed, and the forked child process becomes an orphan process after the parent process commits suicide and is then taken over by the operating system's init process, thus leaving the terminal control.

So in fact, the second fork is not necessary (many of the code in the Open source project will not fork two times). Just for the sake of careful consideration, prevent the process from opening a control terminal again. Because the child process is now the conversation leader (the first session of the conversation), have the ability to open the control terminal, and then fork again, grandson process can not open the control terminal.

File descriptor

Linux is "All Files", and file descriptors are indexes created by the kernel for open files, usually non-negative integers. The process performs IO operations through file descriptors.

Each process has its own file descriptor, so the same descriptor may point to the same file or to a different file, different descriptors from different processes, and, of course, to the same file.

By default, 0 represents standard input, 1 represents standard output, and 2 represents a standard error.

Umask Permission Mask

We know that in Linux, any file has three usage permissions for read (read), write, and execute (execute). Where the Read permission is represented by the number 4, the Write permission is 2, and the execution permission is 1. The command ls-l can view file permissions, r/w/x respectively, with read/write/execute permissions.

Any file, there are three kinds of identity permissions for users (user), user groups (group), and other groups (Others). Typically 3 numbers indicate file permissions, such as 754:

7, is user permission, that is, file owner permissions

5, is the group permission, the owner of the user group members have the permissions

4, is others permissions, that is, the permissions of other groups of users

The umask is to control the default permissions and prevent new files or folders from having full ownership.

The system generally defaults to 022 (viewed with command umask), which means that the default file creation permission is 644 and the folder is 755. You should be able to see the rules, that is, the file permissions and umask add up to 666 (laughter), folder permissions and umask Add the result is 777.

Process Group

Each process belongs to a process group (pg,process Group), and the process group can contain multiple processes.

The process group has a process leader (Leader), the ID of the process leader (PID, process ID) as the ID of the entire process group (pgid,process groupd ID).

Conversation Group

When a terminal is logged in, a session is created, and multiple process groups can be included in a session. And the process of creating a session is the conversation leader.

The session leader is already a process, and the Setsid () method can no longer be called to create the session. Thus, in the code above, the child process can call Setsid (), and the parent process cannot, because it is itself the conversation leader.

In addition, the SH (Bourne shell) does not support the session mechanism because the session mechanism requires the Shell to support work control.

Daemons and daemon processes

With the & symbol, commands can be placed in the background to execute. It is different from the daemon:

1, the daemon is not related to the terminal, is the process of orphans adopted by the INIT process, and the parent process of the background process is the terminal, can still print at the terminal

2, the daemon is still strong when the terminal is closed, and the background process will stop with the user exit, unless added nohup

3, the daemon changes the session, process group, working directory and file descriptor, the background process directly inherits the parent process (shell)

In other words: The Guardian process is a silent struggle to fight for the youth, and then the process is silently inherit the wealth of the second generation of father.

Related Article

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.