Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Signal processing method in python

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "signal processing methods in python", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "signal processing methods in python" article.

What is a signal?

Signal (signal)-A way of interprocess communication, which can also be used as a method of software interruption. Once a process receives a signal, it interrupts the execution of the original program to process it according to the signal.

To simplify the term, a signal is an event that interrupts the execution of a running function. The signal is always executed in the main Python thread. The signal is not described in detail here.

Python encapsulates the operating system's signal function library singal library. The singal library enables us to implement the signal mechanism in python programs.

Signal processing of Python

First of all, you need to understand why Python provides signal Library. The semaphore enables us to use signal handlers so that custom tasks can be performed when a signal is received.

Mission: performs signal processing when a signal is received

You can do this by using the signal.singal () function

Signal processing by Python

Typically, the Python signal handler is always executed in the main thread of the main Python parser, even if the signal is received in another thread. This means that signals cannot be used as a means of communication between threads. You can use the synchronization primitive in the threading module instead.

Python signal processing flow, need to signal processing program (signal handling) brief description. Signal handling is a task or program that requires two parameters when a specific signal is detected, namely, the signal id signal number (1-64 in Linux) and the stack frame frame. The corresponding signal handling is started by the corresponding signal, and signal.signal () will assign the processing function to the signal.

For example, when running a script, cancel, at this time is to capture a signal, you can capture the signal by the way of asynchronous elegant processing of the program. By registering the signal handler with the application:

Import signal import time def handler (a, b): # define a signal handling print ("Signal Number:", a, "Frame:", b) signal.signal (signal.SIGINT, handler) # assign handle to the corresponding signal while True: print ("Press ctrl + c") time.sleep (10)

If the corresponding signal is not captured and processed, python will throw an exception.

Root@Seal:/mnt/d/pywork/signal# python signals. Py^ CTraceback (most recent call last): File "signal.py", line 3, in while True:KeyboardInterrupt signal enumeration

The signal is represented by an int,Python semaphore with corresponding signal enumeration members.

The most commonly used ones are

SIGINT control+c

SIGTERM termination process software termination signal

SIGKILL terminates the process and kills the process

SIGALRM timeout

Signal description SIG_DFL

The SIG_IGN standard signal processor, which simply ignores the SIGABRT SIGIOT stop signal from abort for the given signal.

Abort caused the abnormal process to terminate. It is usually called by library functions that detect internal errors or seriously break constraints. For example, if the internal structure of the heap is damaged by a heap overflow, malloc () calls abort () SIGALRM

SIGVTALRM

SIGPROF if you set a time limit with an alarm setting function such as setitimer, the process will receive SIGALRM, SIGVTALRM or SIGPROF when the time limit is reached. But the meanings of these three semaphores are different. SIGALRM timing is real time, SIGVTALRM timing is how much CPU time the process is using, and SIGPROF timing is how much time is spent by the process and the kernel that represents the process. When an error occurs on the SIGBUS bus, the process receives a SIGBUS signal. For example, SIGBUS signals are generated when memory access is aligned or there is no corresponding physical address. SIGCHLD when a child process terminates, is interrupted, or resumes after being interrupted, SIGCHLD signals are sent to the process. A common use of this signal is to instruct the operating system to clean up the resources used by a child process after it terminates without explicitly calling to wait for a system call. Illegal SIGILL instruction. SIGILL signals are sent to a process when it attempts to execute illegal, malformed, unknown, or privileged instructions. SIGKILL sends SIGKILL signals to a process to cause it to terminate immediately (KILL). Unlike SIGTERM and SIGINT, this signal cannot be captured or ignored, and the receiving process cannot perform any cleanup when it is received. The following exceptions apply: SIGINT comes from a keyboard interrupt (CTRL + C). KeyboardInterruptSIGPIPE SIGPIPE signals are sent to a process when it attempts to write to a pipe that is not connected to the other end of the process. * * SIGTERM * * termination signal. KILL-15 | KILLSIGUSR1

SIGUSR2 user customized signal SIGWINCH terminal window size changed SIGHUP detected suspension or termination of the control process on the control terminal.

Reference: [signal-wikipedia] (

Signal function

There are also many commonly used functions in the signal library of Python.

Signal.alarm (time)

Create a SIGALRM type signal with time as the predetermined time and cancel the previously set timer when it is set to 0

Signal.pause ()

You can make the code logic process sleep until the signal is received, and then call the corresponding handler.

Import signalimport osimport timedef do_exit (sig, stack): raise SystemExit ("Exiting") signal.signal (signal.SIGINT, signal.SIG_IGN) signal.signal (signal.SIGUSR1, do_exit) print ("My PID:", os.getpid ()) signal.pause ()

When executing, ignore the signal of ctrl + c and do the exit operation to USR1.

Signal.setitimer (which, seconds, interval)

Which: signal.ITIMER_REAL,signal.ITIMER_VIRTUAL or signal.ITIMER_PROF

Seconds: how many seconds before which is triggered. Set seconds to 0 to clear the timer for which.

Interval: triggered every interval second

Os.getpid ()

Get the pid of the currently executing program

The use of signal under Windows

In Linux, any acceptable signal enumeration value can be used as a parameter of the signal function. In Windows, SIGABRT, SIGFPE, SIGINT, SIGILL, SIGSEGV, SIGTERM, SIGBREAK.

What to do when signal handling needs parameters

In some cases, the operation of signal handling needs to pass in some functions corresponding to the main process, and the variables executed throughout the project are not in the same scope as signal handling, and signal.signal () cannot pass other parameters, so you can use partial to create a closure to solve this problem.

For example:

Import signalimport osimport sysimport timefrom functools import partial "" here signal frame default parameters need to be put last "" def signal_handler (test_parameter1, test_parameter2, signal_num, frame): print "signal {} exit. {} {}" .format (signal_num, test_parameter1, test_parameter2) sys.exit (1) a=1b=2signal.signal (signal.SIGINT, partial (signal_handler, a, b) print ("My PID:", os.getpid ()) signal.pause () ignores the signal

Signal defines a method to ignore received signals. In order to achieve signal processing, it is necessary to use signal.signal () to register the default signal with signal.SIG_IGN, so that the corresponding signal interrupt can be ignored, and kill-9 can not be ignored.

Import signalimport osimport timedef receiveSignal (signalNumber, frame): print ("Received:", signalNumber) raise SystemExit ("Exiting") returnif _ _ name__ = = "_ _ main__": # register the signal to be caught signal.signal (signal.SIGUSR1, receiveSignal) # register the signal to be ignored signal.signal (signal.SIGINT, signal.SIG_IGN) # output current process id print ("My PID is:", os.getpid () signal.pause ()

Import signalimport osimport timeimport sysdef readConfiguration (signalNumber, frame): print ("(SIGHUP) reading configuration") returndef terminateProcess (signalNumber, frame): print ("(SIGTERM) terminating the process") sys.exit () def receiveSignal (signalNumber, frame): print ("Received:", signalNumber) return signal.signal (signal.SIGHUP, readConfiguration) signal.signal (signal.SIGINT, receiveSignal) signal.signal (signal.SIGQUIT, receiveSignal) signal.signal (signal.SIGILL ReceiveSignal) signal.signal (signal.SIGTRAP, receiveSignal) signal.signal (signal.SIGABRT, receiveSignal) signal.signal (signal.SIGBUS, receiveSignal) signal.signal (signal.SIGFPE, receiveSignal) # signal.signal (signal.SIGKILL, receiveSignal) signal.signal (signal.SIGUSR1, receiveSignal) signal.signal (signal.SIGSEGV, receiveSignal) signal.signal (signal.SIGUSR2, receiveSignal) signal.signal (signal.SIGPIPE, receiveSignal) signal.signal (signal.SIGALRM ReceiveSignal) signal.signal (signal.SIGTERM, terminateProcess) above is the content of this article on "signal processing methods in python" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report