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: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment