Home > Backend Development > Python Tutorial > Python uses the signal module to implement scheduled execution

Python uses the signal module to implement scheduled execution

高洛峰
Release: 2016-10-17 16:51:40
Original
1470 people have browsed it

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 knowledge of signals...

Check which signals your Linux 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 way of communication between processes, it 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

The signal package defines each signal name and its corresponding integer. For example,

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

The signal names used by Python are consistent with 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.

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

$python test.py
Copy after login

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 the SIGALRM signal to the process itself after a certain period of 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')
Copy after login

We use an infinite loop here so that Keep the process running. After signal.alarm() is executed for 5 seconds, the process will send the SIGALRM signal to itself, and then the signal processing function myHandler begins to execute.

发送信号

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包被增强,信号阻塞等功能被加入到该包中。我们暂时不深入到该包中。


source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template