Preliminary understanding of Python process signal communication and python process Signal

Source: Internet
Author: User
Tags sigint signal

Preliminary understanding of Python process signal communication and python process Signal

Signal Concept

Signal: a means of communication between processes. It is a software interruption. Once a process receives a signal, it will interrupt the original program execution process to process the signal.

Several common signals:

SIGINT terminates the process to interrupt the process (control + c)

SIGTERM termination process software termination signal

SIGKILL terminate the process and kill the process

SIGALRM alarm signal
Difference between process end signal SIGTERM and SIGKILL

SIGTERM is relatively friendly, and processes can capture this signal and close the program as needed. Before closing the program, you can end the opened record file and complete ongoing tasks. In some cases, if the process is running and cannot be interrupted, the process can ignore this SIGTERM signal.

Processes cannot ignore SIGKILL signals. This is a signal "I don't care what you are doing, stop immediately. If you send a SIGKILL signal to the process, Linux stops the process.
There are two reasons for sending signals:

1 (passive) the kernel detects a system event. For example, if a sub-process exits, it will send a SIGCHLD signal like a parent process. Pressing control + c on the keyboard will send a SIGINT signal.

2 (active) sends signals to a specified process by calling kill.
Signals provided by linux

[100003 @ oss235 myppt] $ 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)

55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6

59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62)

63) SIGRTMAX-1 64) SIGRTMAX

Signals provided by Python

Python 2.4.3 (#1, Jun 11 2009, 14:09:58)[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import signal>>> dir(signal)['NSIG', 'SIGABRT', 'SIGALRM', 'SIGBUS', 'SIGCHLD', 'SIGCLD', 'SIGCONT', 'SIGFPE', 'SIGHUP', 'SIGILL', 'SIGINT', 'SIGIO', 'SIGIOT', 'SIGKILL', 'SIGPIPE', 'SIGPOLL', 'SIGPROF', 'SIGPWR', 'SIGQUIT', 'SIGRTMAX', 'SIGRTMIN', 'SIGSEGV', 'SIGSTOP', 'SIGSYS', 'SIGTERM', 'SIGTRAP', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU', 'SIGURG', 'SIGUSR1', 'SIGUSR2', 'SIGVTALRM', 'SIGWINCH', 'SIGXCPU', 'SIGXFSZ', 'SIG_DFL', 'SIG_IGN', '__doc__', '__name__', 'alarm', 'default_int_handler', 'getsignal', 'pause', 'signal']

The operating system specifies the default behavior after the process receives the signal

However, we can bind a signal processing function to modify the process's behavior after receiving the signal.

Two signals are unchangeable: SIGTOP and SIGKILL.
Bind signal processing functions

Import OS import signal from time import sleep def onsignal_term (a, B): print 'receive SIGTERM sign' # Here is the binding signal processing function, which binds SIGTERM TO THE onsignal_term function. signal (signal. SIGTERM, onsignal_term) def onsignal_usr1 (a, B): print 'receive SIGUSR1 sign' # Here is the signal processing function bound to SIGUSR1 ON THE onsignal_term function signal. signal (signal. SIGUSR1, onsignal_usr1) while 1: print 'my process id is ', OS. getpid () sleep (10)

Run the program. Then, a signal is sent through another process.
Send signal

The code for sending signals is as follows:

Import OS import signal # Sends the signal. 16175 is the pid bound to the signal processing function. You need to modify the OS on your own. kill (16175, signal. SIGTERM) # Send the signal. 16175 is the pid bound to the signal processing function. You need to modify the OS on your own. kill (16175, signal. SIGUSR1)

SIGCHLD Signal

An example of automatically sending a SIGCHLD signal to the parent process after the child process ends is displayed.

''''' The child process ends and sends the SIGCHLD signal '''import OS import signal from time import sleep def onsigchld (a, B) to the parent process ): print 'receive the subprocess terminate' signal. signal (signal. SIGCHLD, onsigchld) pid = OS. fork () if pid = 0: print 'I am a sub-process, pid is', OS. getpid () sleep (2) else: print 'I am the parent process, pid is', OS. getpid () OS. wait () # wait until the child process ends

Note the following when using signals:

If a process receives a SIGUSR1 signal and then executes the signal binding function, the second SIGUSR2 signal returns. If the first signal is not processed, the second signal is discarded.

Therefore, do not use signals in multiple threads.

This is not correct. No signal is lost in the test.

Example:

The program that receives signals, you will find that if another end uses multiple threads to send signals to this process, some signals will be missed.

Import OS import signal from time import sleep import Queue QCOUNT = Queue. queue () # initialize the Queue def onsigchld (a, B ): ''''''' insert a number into the queue after receiving the signal. 1 '''print 'receives the SIGUSR1 signal 'sleep (2) QCOUNT. put (1) # Write def exithanddle (s, e) to the queue: raise SystemExit ('receive the termination command and exit the put') signal. signal (signal. SIGUSR1, onsigchld) # bind the signal processing function signal. signal (signal. SIGINT, exithanddle) # When you press Ctrl + C to terminate the process while 1: print 'my pid is ', OS. getpid () print 'number of elements in the queue is ', QCOUNT. qsize () sleep (2)

Multi-thread signal sending program:

 

''''' Use multiple threads to send signals to another process ''' import threading import OS import signal def sendusr1 (): print 'send sign' # The process id here needs to write the pid OS actually running in the previous program. kill (17788, signal. SIGUSR1) WORKER = [] # enable six threads for I in range (1, 7): threadinstance = threading. thread (target = sendusr1) WORKER. append (threadinstance) for I in WORKER: I. start () for I in WORKER: I. join () print 'main thread completed'

Content supplement:

Alarms is a special signal type that allows the program to require the system to send notifications to itself after a period of time. It is pointed out in the OS standard module that it can be used to avoid unrestricted blocking of I/O operations or other system calls.

In the following example, print 'after: ', time. ctime (), but because of signal. alarm (2), so the printing will be executed in 2 seconds.

  import signal   import time      def receive_alarm(signum, stack):     print 'Alarm :', time.ctime()      # Call receive_alarm in 2 seconds   signal.signal(signal.SIGALRM, receive_alarm)   signal.alarm(2)      print 'Before:', time.ctime()   time.sleep(10)   print 'After :', time.ctime()  

Note that only the main thread of Signal can receive signals. In the following example, the print 'done waiting' statement cannot be printed. IF signal. alarm (2) is not called, the program will be blocked forever.

  import signal   import threading   import os   import time      def signal_handler(num, stack):     print 'Received signal %d in %s' % \       (num, threading.currentThread().name)      signal.signal(signal.SIGUSR1, signal_handler)      def wait_for_signal():     print 'Waiting for signal in', threading.currentThread().name     signal.pause()     print 'Done waiting'      # Start a thread that will not receive the signal   receiver = threading.Thread(target=wait_for_signal, name='receiver')   receiver.start()   time.sleep(0.1)      def send_signal():     print 'Sending signal in', threading.currentThread().name     os.kill(os.getpid(), signal.SIGUSR1)      sender = threading.Thread(target=send_signal, name='sender')   sender.start()   sender.join()      # Wait for the thread to see the signal (not going to happen!)   print 'Waiting for', receiver.name   signal.alarm(2)   receiver.join() 

Note that, although alarms signals can be called in any thread, they can only be received in the main thread, as in the following example, even if the sub-thread use_alarm calls signal. alarm (1), but does not work:

  import signal   import time   import threading      def signal_handler(num, stack):     print time.ctime(), 'Alarm in', threading.currentThread().name      signal.signal(signal.SIGALRM, signal_handler)      def use_alarm():     t_name = threading.currentThread().name     print time.ctime(), 'Setting alarm in', t_name     signal.alarm(1)     print time.ctime(), 'Sleeping in', t_name     time.sleep(3)     print time.ctime(), 'Done with sleep in', t_name      # Start a thread that will not receive the signal   alarm_thread = threading.Thread(target=use_alarm,                   name='alarm_thread')   alarm_thread.start()   time.sleep(0.1)      # Wait for the thread to see the signal (not going to happen!)   print time.ctime(), 'Waiting for', alarm_thread.name   alarm_thread.join()      print time.ctime(), 'Exiting normally' 

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.