search
HomeBackend DevelopmentPython TutorialPython uses the signal module to implement scheduled execution

In the liunx system, if you want to execute a command every minute, the most common method is crontab. If you don’t want to use crontab, my colleagues pointed out that you can use a timer to achieve this function in the program, so I started to explore and found out. You need some signal knowledge...

Check which signals your linux supports: kill -l can

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:~#

Signal: The way 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 the SIGCHLD signal to the parent process. Pressing control+c on the keyboard will send the SIGINT signal

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

There is a setitimer function in C language. The function setitimer can provide three timers, which are independent of each other. When any time is completed, a timing signal will be sent to the process and automatically Reset time. 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

These three 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 alarm function essentially sets a low-precision, non-overloaded ITIMER_REAL timer. It can only be accurate to seconds, and can only generate one timer per setting. The timers set by the function setitimer are different. They can not only time to microseconds (theoretically), but also automatically cycle the time. In a Unix process, alarm and ITIMER_REAL timers cannot be used at the same time.

SIGINT Terminate the process Interrupt the process (control+c)

SIGTERM Terminate the process Software terminate signal

SIGKILL Terminate the process Kill the process

SIGALRM Alarm clock signal

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

Define signal names

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

import signal
print signal.SIGALRM
print signal.SIGCONT

The signal names used by Python are the same as Linux. You can query the

preset signal processing function through

$man 7 signal

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)

signalnum is a certain 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')

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.

The above program can be saved in a file (such as test.py). We use the following method to run:

$python test.py

to let the process run. When the program reaches signal.pause(), the process pauses and waits for the signal. At this point, send the SIGTSTP signal to the process by pressing CTRL+Z. We can see that the process executes the myHandle() function, then returns to the main program and continues execution. (Of course, you can also use $ps to query the process ID, and then use $kill to send the signal.)

(The process does not have to use signal.pause() to pause to wait for the signal, it can also receive the signal while working, For example, change the signal.pause() above into a loop that takes a long time to work. )

We can change the operations in myHandler() according to our own needs to achieve personalized processing for different signals.

Send SIGALRM signal regularly

A useful function is signal.alarm(), which is used to send SIGALRM signal to the process itself after a certain time:

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')

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

发送信号

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

os.kill(pid, sid)
os.killpg(pgid, sid)

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

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

Statement
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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.