Python uses the signal module for timed execution

Source: Internet
Author: User
Tags sigint signal signal handler
In the LIUNX system in order to execute a command every minute, the most common way is crontab, if you do not want to use Crontab, with colleagues in the program can use the timer to achieve this function, so began to grope, found that need some signal knowledge ...

See 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) SIGUSR111) SIGSEGV) (SIGUSR2) sigpipe) sigalrm) SIGTERM16) Sigstkflt 17)  SIGCHLD) (Sigcont) SIGSTOP) SIGTSTP21) sigttin) Sigttou Sigurg) Sigxcpu 25) SIGXFSZ26) (SIGVTALRM) sigprof) sigwinch SIGIO) SIGPWR31 Sigsys) sigrtmin tmin+1) sigrtmin+2 (Panax Notoginseng) sigrtmin+338) sigrtmin+4 () sigrtmin+5) sigrtmin+6) sigrtmin+7) SI grtmin+9) (sigrtmin+10) sigrtmin+11 () sigrtmin+12) sigrtmin+1348) sigrtmin+14) sigrtmin+15 5   1) SIGRTMAX-13 () SIGRTMAX-1253) SIGRTMAX-11 SIGRTMAX-10) SIGRTMAX-9) SIGRTMAX-8) SIGRTMAX-758 () SIGRTMAX-5) SIGRTMAX-4 () SIGRTMAX-3) SIGRTMAX-263) SIGRTMAX-1

Signal: The way communication between processes is a software interrupt. Once a process receives a signal, it interrupts the original program execution process to process the signal. The operating system specifies the default behavior after a process receives a signal, but we can modify the behavior of the process after it receives the signal by binding the signal handler function, and there are two signals that are immutable sigtop and Sigkill.

There are two general reasons for sending a signal:

1 (passive) The kernel detects a system event. For example, a child process exit sends a SIGCHLD signal like a parent process. Keyboard presses CONTROL+C sends SIGINT signal

2 (Active) sends a signal to the specified process via system call Kill

In C language There is a Setitimer function, function Setitimer can provide three kinds of timers, they are independent of each other, any one timing completion will send a timing signal to the process, and automatically re-timer. The parameter which determines the type of timer:

Itimer_real timed real time, same as alarm type. Sigalrm

Itimer_virt the actual execution time of the timed process in the user state. Sigvtalrm

Itimer_prof the actual execution time of the timed process in the user state and kernel mentality. Sigprof

When these three kinds of timers are timed to complete, the signal sent to the process is different, wherein 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 class timer, which can only be accurate to seconds, and can only be timed once per set. The timers set by the function Setitimer are different, they can not only be timed to subtle (theoretically), but can also be automatically cycled and timed. In a UNIX process, you cannot use both the alarm and the Itimer_real class timers.

SIGINT terminating process interrupt process (CONTROL+C)

SIGTERM terminating process software termination signal

SIGKILL Terminate process Kill process

SIGALRM Alarm Clock signal

The pre-knowledge is almost ready, and it's time to march into Python's signal.

Define the signal name

The signal package defines the individual signal names and their corresponding integers, such as

Import Signalprint signal. Sigalrmprint signal. Sigcont

Python uses the same signal name as Linux. You can pass

$man 7 Signal

Inquire

Preset Signal processing functions

The core of the signal package is to use the signal.signal () function to preset the (register) signal processing function as follows:

Singnal.signal (Signalnum, handler)

Signalnum is a signal, handler is the processing function of the signal. We mentioned in the signal base that the process can ignore the signal, can take the default action, and can customize the operation. When handler is signal. Sig_ign, the signal is ignored (ignore). When handler is Singal. SIG_DFL, the process takes the default action. When handler is a function name, the process takes the action defined in the function.

Import signal# Define Signal handler functiondef MyHandler (Signum, frame):  print (' I received: ', Signum)  # regist ER 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. We then execute Signal.pause () to let the process pause to wait for the signal. When the signal SIGUSR1 is passed to the process, the process resumes from the pause and, according to the preset, executes the SIGTSTP signal handler function MyHandler (). MyHandler two parameters one is used to identify the signal (Signum), and the other is used to obtain the status of the process stack when the signal occurs (stack frame). Both of these 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

For the process to run. When the program runs to Signal.pause (), the process pauses and waits for a signal. At this point, a SIGTSTP signal is sent to the process by pressing CTRL + Z. As we can see, the process executes the myhandle () function, which is then returned to the main program to continue execution. (Of course, you can also query the process ID with $ps, and then use $kill to signal.) )

(The process does not have to use Signal.pause () to pause to wait for a signal, it can also accept signals in the work, such as changing the above signal.pause () to a cycle that takes a long time to work. )

We can change the operations in MyHandler () to suit our needs to personalize the processing for different signals.

Timing out SIGALRM Signals

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

Import signal# Define Signal handler functiondef 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 ')

We use an infinite loop here to keep the process running. After Signal.alarm () executes for 5 seconds, the process sends itself a SIGALRM signal, and then the signal handler function MyHandler begins execution.

Send Signal

The core of the signal package is to set the signal processing function. In addition to the Signal.alarm () sends a signal to itself, there is no other function to send the signal. In the OS package, however, there are functions similar to the Linux Kill command, respectively

Os.kill (PID, sid) Os.killpg (Pgid, sid)

Send signals to process and process groups (see Linux process Relationships), respectively. The SID is the integer or singal that corresponds to the signal. sig*.

In fact, signal, pause,kill and alarm are all common C library functions in Linux application programming, and here we are only implementing them in Python language. In fact, Python's interpreter is written in C, so this similarity is not surprising. In addition, in Python 3.4, the signal package is enhanced, and the signal blocking feature is added to the package. We do not dive into the package for the time being.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.