Home Backend Development Python Tutorial Detailed explanation of how Python uses the signal module to implement scheduled execution methods

Detailed explanation of how Python uses the signal module to implement scheduled execution methods

Mar 19, 2017 pm 03:24 PM
python

In the liunx system, if you want to execute a command every one minute, the most common method is crontab. If you don't want to use crontab, you can use timer to achieve this function in the program as instructed by a colleague. , so I started to explore and found that I need some knowledge of signals...

Check which signals yourlinux supports: kill -l

root@server:~# kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL     10) SIGUSR1
11) SIGSEGV     12) SIGUSR2     13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGSTKFLT   17) SIGCHLD     18) SIGCONT     19) SIGSTOP     20) SIGTSTP
21) SIGTTIN     22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO       30) SIGPWR
31) SIGSYS      34) SIGRTMIN    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3
38) SIGRTMIN+4  39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7
58) SIGRTMAX-6  59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX
root@server:~#
Copy after login

Signal: The method of communication between processes is a software interrupt. Once a process receives a signal, it interrupts the original program execution flow to process the signal. The operating system stipulates the default behavior of the process after receiving the signal. However, we can modify the behavior of the process after receiving the signal by binding the signal processing function. There are two signals that cannot be changed, SIGTOP and SIGKILL.

There are generally two reasons for sending signals:

1 (Passive) The kernel detects a system event. For example, when the child process exits, it will send SIGCHLD to the parent process. Signal. Pressing control+c on the keyboard will send the SIGINT signal

2 (active). Send a signal to the specified process through the system call kill

In C language There is a setitimer function. The function setitimer can provide three timers, which are independent of each other. When any timer is completed, a timing signal will be sent to the process and the timer will be automatically retimed. The parameter which determines the type of timer:

ITIMER_REAL Timing real time, the same as the alarm type. SIGALRM

ITIMER_VIRT The actual execution time of the scheduled process in user mode. SIGVTALRM

ITIMER_PROF The actual execution time of the scheduled process in user mode and core mode. SIGPROF

The three types of timers send different signals to the process when the timing is completed. Among them, the ITIMER_REAL class timer sends the SIGALRM signal, the ITIMER_VIRT class timer sends the SIGVTALRM signal, and the ITIMER_REAL class timer sends the SIGPROF signal.

The function alarm essentially sets a low-precision, non-overloaded ITIMER_REAL timer. It can only be accurate to seconds, and each setting can only generate timing once. The timers set by the function setitimer are different. Not only can they time to microseconds (theoretically), but they can also automatically cycle the timer. In a Unix process, alarm and ITIMER_REAL timers cannot be used at the same time.

SIGINT Terminate process Interrupt process (control+c)

SIGTERM Terminate process Software termination signal

SIGKILL Terminate process Kill process

SIGALRM Alarm clock signal

The preliminary knowledge is almost ready, and it’s time to move towards python’s signal.

Define signal names

The signal package defines each signal name and its corresponding integer, such as

import signal
print signal.SIGALRM
print signal.SIGCONT
Copy after login

The signal name used by Python is the same as Linux. You can query the preset signal processing function through

$man 7 signal
Copy after login

The core of the signal package is to use the signal.signal() function to preset (register) the signal processing function. As shown below:

singnal.signal(signalnum, handler)
Copy after login

signalnum is a signal, and handler is the processing function of the signal. We mentioned in the signal basics that a process can ignore signals, take default actions, or customize actions. When handler is signal.SIG_IGN, the signal is ignored. When the handler is singal.SIG_DFL, the process takes the default action (default). When handler is a function name, the process takes the action defined in the function.

import signal
# Define signal handler function
def myHandler(signum, frame):
  print('I received: ', signum)
 
# register signal.SIGTSTP's handler 
signal.signal(signal.SIGTSTP, myHandler)
signal.pause()
print('End of Signal Demo')
Copy after login

In the main program, we first use the signal.signal() function to preset the signal processing function. Then we execute signal.pause() to pause the process waiting for the signal to wait for the signal. When the signal SIGUSR1 is passed to the process, the process resumes from the pause and executes the SIGTSTP signal processing function myHandler() according to the default. One of the two parameters of myHandler is used to identify the signal (signum), and the other is used to obtain the status of the process stack (stack frame) when the signal occurs. Both parameters are passed by the signal.singnal() function.

上面的程序可以保存在一个文件中(比如test.py)。我们使用如下方法运行:

$python test.py
Copy after login

以便让进程运行。当程序运行到signal.pause()的时候,进程暂停并等待信号。此时,通过按下CTRL+Z向该进程发送SIGTSTP信号。我们可以看到,进程执行了myHandle()函数, 随后返回主程序,继续执行。(当然,也可以用$ps查询process ID, 再使用$kill来发出信号。)

(进程并不一定要使用signal.pause()暂停以等待信号,它也可以在进行工作中接受信号,比如将上面的signal.pause()改为一个需要长时间工作的循环。)

我们可以根据自己的需要更改myHandler()中的操作,以针对不同的信号实现个性化的处理。

定时发出SIGALRM信号

一个有用的函数是signal.alarm(),它被用于在一定时间之后,向进程自身发送SIGALRM信号:

import signal
# Define signal handler function
def myHandler(signum, frame):
  print("Now, it's the time")
  exit()
 
# register signal.SIGALRM's handler 
signal.signal(signal.SIGALRM, myHandler)
signal.alarm(5)
while True:
  print('not yet')
Copy after login

我们这里用了一个无限循环以便让进程持续运行。在signal.alarm()执行5秒之后,进程将向自己发出SIGALRM信号,随后,信号处理函数myHandler开始执行。 

发送信号

signal包的核心是设置信号处理函数。除了signal.alarm()向自身发送信号之外,并没有其他发送信号的功能。但在os包中,有类似于linux的kill命令的函数,分别为

os.kill(pid, sid)
os.killpg(pgid, sid)
Copy after login

分别向进程和进程组(见Linux进程关系)发送信号。sid为信号所对应的整数或者singal.SIG*。

实际上signal, pause,kill和alarm都是Linux应用编程中常见的C库函数,在这里,我们只不过是用Python语言来实现了一下。实际上,Python 的解释器是使用C语言来编写的,所以有此相似性也并不意外。此外,在Python 3.4中,signal包被增强,信号阻塞等功能被加入到该包中。我们暂时不深入到该包中。

The above is the detailed content of Detailed explanation of how Python uses the signal module to implement scheduled execution methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles