Daemon: Usually defined as a background process, and it does not belong to any terminal session (terminal session). Many system services are implemented by daemons; such as network services, printing, etc. The following article shares with you an example of how Python implements a daemon process. Friends in need can refer to it.
Scenario setting:
You wrote a python service program and started it from the command line, and your command line session was Controlled by the terminal, the python service becomes a sub-process of the terminal program. So if you close the terminal, the command line program will also close.
To make your python service permanent in the system without being affected by the terminal, you need to turn it into a daemon process.
The daemon process is a Daemon program, which is a program executed in the background of the system. It is independent of the control terminal and performs some periodic tasks or triggers events. It is usually named after the letter "d", such as Common httpd, syslogd, systemd and dockerd, etc.
Code implementation
Python can implement the daemon process very simply. The code and corresponding comments are given below:
# coding=utf8 import os import sys import atexit def daemonize(pid_file=None): """ 创建守护进程 :param pid_file: 保存进程id的文件 :return: """ # 从父进程fork一个子进程出来 pid = os.fork() # 子进程的pid一定为0,父进程大于0 if pid: # 退出父进程,sys.exit()方法比os._exit()方法会多执行一些刷新缓冲工作 sys.exit(0) # 子进程默认继承父进程的工作目录,最好是变更到根目录,否则回影响文件系统的卸载 os.chdir('/') # 子进程默认继承父进程的umask(文件权限掩码),重设为0(完全控制),以免影响程序读写文件 os.umask(0) # 让子进程成为新的会话组长和进程组长 os.setsid() # 注意了,这里是第2次fork,也就是子进程的子进程,我们把它叫为孙子进程 _pid = os.fork() if _pid: # 退出子进程 sys.exit(0) # 此时,孙子进程已经是守护进程了,接下来重定向标准输入、输出、错误的描述符(是重定向而不是关闭, 这样可以避免程序在 print 的时候出错) # 刷新缓冲区先,小心使得万年船 sys.stdout.flush() sys.stderr.flush() # dup2函数原子化地关闭和复制文件描述符,重定向到/dev/nul,即丢弃所有输入输出 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()) # 写入pid文件 if pid_file: with open(pid_file, 'w+') as f: f.write(str(os.getpid())) # 注册退出函数,进程异常退出时移除pid文件 atexit.register(os.remove, pid_file)
Summarize the steps for writing a daemon process:
fork the child process, Exit the parent process
The child process changes the working directory (chdir), file permission mask (umask), process group and session group (setsid)
The child process forks the grandson process and exits the child process
The grandson process refreshes the buffer and redirects standard input/output/error (usually to /dev/null, which means discarding)
(Optional) pid writes to file
Understand several key points
Why fork twice
The first fork is to escape from the clutches of terminal control. The reason why the parent process exits is because the terminal hits the keyboard or sends a signal to it 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 init process of the operating system, so it leaves the terminal. control.
So in fact, the second fork is not necessary (the code in many open source projects does not fork twice). It's just out of caution to prevent the process from opening a control terminal again. Because the child process is now the session leader (the first process in the session) and has the ability to open the control terminal, if it forks again, the grandson process will not be able to open the control terminal.
File descriptor
Linux is "everything is a file". The file descriptor is the index created by the kernel for the open file, usually a non-negative integer. Processes perform IO operations through file descriptors.
By default, 0 represents standard input, 1 represents standard output, and 2 represents standard error.
umask permission mask
We know that in Linux, any file has three functions: read (read), write (write) and execute (execute). kind of usage rights. Among them, the read permission is represented by the number 4, the write permission is 2, and the execution permission is 1. You can check the file permissions with the command ls -l, and r/w/x means you have read/write/execute permissions respectively.
Any file also has three identity permissions: user (User), user group (Group), and other groups (Others). Generally, three numbers are used to represent file permissions, such as 754:
7 is User permission, that is, the file owner permission
5 is Group permission, which is the user group of the owner The permissions of group members
4 are Others permissions, that is, the permissions of users in other groups
And umask is to control the default permissions and prevent new files or files Clamp has full authority.
The system generally defaults to 022 (use the umask command to view), which means that the default permissions for creating files are 644 and folders are 755. You should be able to see their pattern, that is, the sum of file permissions and umask is 666 (laughing), and the sum of folder permissions and umask is 777.
Process Group
Each process belongs to a process group (PG, Process Group), and a process group can contain multiple processes.
The process group has a process leader (Leader), and the ID of the process leader (PID, Process ID) is used as the ID of the entire process group (PGID, Process Groupd ID).
Session Group
When you log in to the terminal, a session will be created. Multiple process groups can be included in one session. The process that creates a session is the session leader.
A process that is already the session leader cannot call the setsid() method to create a session. Therefore, in the above code, the child process can call setsid(), but the parent process cannot because it is the session leader.
In addition, sh (Bourne Shell) does not support the session mechanism, because the session mechanism requires the shell to support job control (Job Control).
Daemon process and background process
With the & symbol, commands can be executed in the background. It is different from the daemon process:
The daemon process has nothing to do with the terminal and is an orphan process adopted by the init process; while the parent process of the background process is the terminal, it can still print on the terminal
The daemon process remains strong when the terminal is closed; the background process will stop when the user exits, unless nohup is added
The daemon process changes the session, process group, working directory and file descriptor , the background process directly inherits the
# of the parent process (shell). In other words: the daemon process is a promising young man who silently works hard, while the background process silently inherits the father's The rich second generation with assets.
For more relevant articles on how to implement daemon processes in Python, please pay attention to the PHP Chinese website!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor