effect : Sending and receiving asynchronous system signals
Signal is an operating system feature , It provides a way to notify a program that an event has occurred and handle it asynchronously . The signal can be generated by the system itself , It can also be sent from one process to another .
Because the signal will interrupt the normal control flow of the program , If a signal is received in the middle , Some operations ( especially I/O operation ) There may be mistakes .
Received signal
signal.signal(sig,action)
sig For a signal ,action Is the processing function of the signal **.**
for example :
signal.signal(signal.SIGALRM, hanlder) hanlder Is the signal processing function
windows Next sig The signal :
>>> dir (signal) [ 'CTRL_BREAK_EVENT' , 'CTRL_C_EVENT' , 'NSIG' , 'SIGABRT' , 'SIGBREAK' , 'SIGFPE' , 'SIGILL' , 'SIGINT' , 'SIGSEGV' , 'SIGTERM' , 'SIG_DFL' , 'SIG_IGN' , '__doc__' , '__name__' , '__package__' , 'default_int_handler' , 'getsignal' , 'set_wakeup_fd' , 'signal' ]
linux Next sig The signal :
>>> dir (signal) [ 'ITIMER_PROF' , 'ITIMER_REAL' , 'ITIMER_VIRTUAL' , 'ItimerError' , '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__' , '__package__' , 'alarm' , 'default_int_handler' , 'getitimer' , 'getsignal' , 'pause' , 'set_wakeup_fd' , 'setitimer' , 'siginterrupt' , 'signal' ]
That is, by establishing a callback function to receive the signal , This callback function is called a signal processing function (signal hanlder), It calls when a signal appears .
signal.signal(sig,action)
SIGUSR1 and SIGUSR2 It's a signal for the user to use .windows There are no two signals .
This script will loop infinitely , Every pause 3 Second . When there's a signal coming ,sleep() The call was interrupted , Signal processing program receive_signal Called . When the signal processor returns , The cycle continues .
os.kill(pid, sig):pid For process number , sig Is the signal
The parent process uses kill() and signal The module sends a signal to the child process . In the parent process , Use kill() Send a USR1 There will be a short pause before the signal , This short pause gives the subprocess time to set up the signal handler .
signal.pause(): Wait until a signal is received
Under normal circumstances ,SIGINT Will produce a KeyboardInterrupt, This example will ignore SIGINT, And find out SIGUSR1 It's time to create a SystemExit.
signal.alarm(time): If time Right and wrong 0, This function responds to a SIGALRM Signal and in time Seconds later to the process .