作用:发送和接收异步系统信号

  信号是一个操作系统特性,它提供了一个途径可以通知程序发生了一个事件并异步处理这个事件。信号可以由系统本身生成,也可以从一个进程发送到另一个进程。

由于信号会中断程序的正常控制流,如果在中间接收到信号,有些操作(特别是I/O操作)可能会发生错误。

接收信号:

  signal.signal(sig,action)

  sig为某个信号,action为该信号的处理函数。

  例如:

    signal.signal(signal.SIGALRM, hanlder)       hanlder为信号处理函数

  windows下sig信号:

  >>> 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下sig信号:

  

  >>> 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']
  >>>

  即通过建立一个回调函数来接收信号,这个回调函数称为信号处理函数(signal hanlder),它会在信号出现时调用。

 信号处理函数包括信号编号及被信号中断那一时刻的栈帧。

  

  def hanlder(signum, frame):

      something...

  signum即信号编号( 数字),例如:

  

  Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
  Type "copyright", "credits" or "license()" for more information.
  >>> import signal
  >>> signal.SIGINT
  2
  >>>

  frame为被信号中断那一时刻的栈帧。

==================================================================

接收信号:signal.signal(sig,action)

官方文档:
signal.signal(signalnum, handler)

Set the handler for signal signalnum to the function handler. handler can be a callable Python object taking two arguments (see below), or one of the special values signal.SIG_IGN or signal.SIG_DFL. The previous signal handler will be returned (see the description of getsignal() above). (See the Unix man page signal(2).)

When threads are enabled, this function can only be called from the main thread; attempting to call it from other threads will cause a ValueError exception to be raised.

The handler is called with two arguments: the signal number and the current stack frame (None or a frame object; for a description of frame objects, see the description in the type hierarchy or see the attribute descriptions in the inspect module).

On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, or SIGTERM. A ValueError will be raised in any other case.

import signal
import os
import time def receive_signal(signum, stack):
print 'Received:', signum # 注册信号处理程序
signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal) # 打印这个进程的PID方便使用kill传递信号
print 'My PID is:', os.getpid() # 等待信号,有信号发生时则调用信号处理程序
while True:
print 'Waiting...'
time.sleep(3)

SIGUSR1和SIGUSR2是留给用户使用的信号。windows下无这两个信号。

这个脚本会无限循环,每次暂停3秒钟。有信号到来时,sleep()调用被中断,信号处理程序receive_signal被调用.信号处理程序返回时,循环继续。

==================================================================

发送信号:os.kill(pid, sig)

>>> import os
>>> help(os.kill)
Help on built-in function kill in module nt: kill(...)
kill(pid, sig) Kill a process with a signal. >>>

pid为进程号, sig为信号

import os
import signal
import time def signal_usr1(signum, frame):
"Callback invoked when a signal is received"
pid = os.getpid()
print 'Received USR1 in process %s' % pid print 'Forking...'
child_pid = os.fork()
if child_pid:
print 'PARENT: Pausing before sending signal...'
time.sleep(1)
print 'PARENT: Signaling %s' % child_pid
os.kill(child_pid, signal.SIGUSR1)
else:
print 'CHILD: Setting up a signal handler'
signal.signal(signal.SIGUSR1, signal_usr1)
print 'CHILD: Pausing to wait for signal'
time.sleep(5)

父进程使用kill()和signal模块向子进程发送信号。在父进程中,使用kill()发送一个USR1信号之前会暂停很短一段时间,这个短暂的暂停使子进程有时间建立信号处理程序。

=================================================================

signal.pause()

官方文档:

signal.pause()

Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Not on Windows. (See the Unix man page signal(2).)

等待直到接收一个信号

import signal
import os
import time def do_exit(sig, stack):
raise SystemExit('Exiting') # 将SIGINT的默认处理程序替换为SIG_IGN
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGUSR1, do_exit) print 'My PID:', os.getpid() signal.pause()

正常情况下,SIGINT会产生一个KeyboardInterrupt,这个例子将忽略SIGINT,并在发现SIGUSR1时产生一个SystemExit。

=================================================================

signal.alarm(time)

官方文档:
signal.alarm(time)

If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If time is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled. (See the Unix man page alarm(2).) Availability: Unix.

如果time是非0,这个函数则响应一个SIGALRM信号并在time秒后发送到该进程。

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

================================================================

python signal信号的更多相关文章

  1. 转:python signal信号

    转自:http://www.jb51.net/article/74844.htm 在liunx系统中要想每隔一分钟执行一个命令,最普遍的方法就是crontab了,如果不想使用crontab,经同事指点 ...

  2. Python Signal 信号

    https://blog.csdn.net/kongxx/article/details/50976802 http://blog.itpub.net/7728585/viewspace-214206 ...

  3. Python——signal

    该模块为在Python中使用信号处理句柄提供支持.下面是一些使用信号和他们的句柄时需要注意的事项: 除了信号 SIGCHLD 的句柄遵从底层的实现外,专门针对一个信号的句柄一旦设置,除非被明确地重置, ...

  4. [开发技巧]·Python实现信号滤波(基于scipy)

    [开发技巧]·Python实现信号滤波(基于scipy) 个人网站--> http://www.yansongsong.cn GitHub主页--> https://github.com/ ...

  5. python使用信号机制实例:

    python使用信号机制实例: 程序会一直等待,直到其他程序发送CTRL-C信号给本进程.需要其他程序配合测试. 或者打开新的终端使用kill -sig PID 向一个进程发送信号,来测试. from ...

  6. Inside Flask - signal 信号机制

    Inside Flask - signal 信号机制 singal 在平常的 flask web 开发过程中较少接触到,但对于使用 flask 进行框架级别的开发时,则必须了解相关的工作机制.flas ...

  7. signal信号

    1.signal信号调试 http://hongjiang.info/shell-script-background-process-ignore-sigint/

  8. linux信号Linux下Signal信号太详细了,终于找到了

    linux信号Linux下Signal信号太详细了,终于找到了 http://www.cppblog.com/sleepwom/archive/2010/12/27/137564.html

  9. python signal(信号)

    信号的概念 信号(signal)--     进程之间通讯的方式,是一种软件中断.一个进程一旦接收到信号就会打断原来的程序执行流程来处理信号. 几个常用信号: SIGINT     终止进程  中断进 ...

随机推荐

  1. Atitit.gui api自动化调用技术原理与实践

    Atitit.gui api自动化调用技术原理与实践 gui接口实现分类(h5,win gui, paint opengl,,swing,,.net winform,)1 Solu cate1 Sol ...

  2. fir.im Weekly - 2016 年 Android 最佳实践列表

    2016 年已经过去一半,你在年初制定的成长计划都实现了吗? 学海无涯,技术成长不是一簇而就的事情.本期 fir.im Weekly 推荐 王下邀月熊_Chevalier的 我的编程之路--知识管理与 ...

  3. iOS--------坐标系统(UIView的frame、bounds跟center属性)

    1.概要翻开ios官方开发文档,赫然发现上面对这三个属性的解释如下: frame:描述当前视图在其父视图中的位置和大小. bounds:描述当前视图在其自身坐标系统中的位置和大小. center:描述 ...

  4. CKEditor Html Helpers for ASP.NET MVC3 Razor/WebForms Views

    一.原生方法: 在 razor 中 使用Fckeditor 编辑内容,需要引入js <script src="@Url.Content("~/fckeditor/fckedi ...

  5. KnockoutJS 3.X API 第四章 数据绑定(2) 控制流foreach绑定

    foreach绑定 foreach绑定主要用于循环展示监控数组属性中的每一个元素,一般用于table标签中 假设你有一个监控属性数组,每当您添加,删除或重新排序数组项时,绑定将有效地更新UI的DOM- ...

  6. Python之函数与变量

    本节内容 函数介绍及其作用 函数的定义与调用 函数的参数说明 全局变量与局部变量 值传递和引用传递 一.函数的介绍及其作用 编程语言中的函数与数学中的函数是有区别的:数学中的函数有参数(输入),就会有 ...

  7. APP 版本更新 流程(已上架APP,提交新版本)

    背景: 今天发布app的新版本, 可是无奈换了电脑, 没有了以前上架时候的发布证书和描述文件. 但是没关系, 依然可以上传成功,哈哈哈~ 虽然走了很多弯路 - -|| 如果是向 App Store 提 ...

  8. 探讨Nodejs中的作用域问题。

    在JS中有全局作用域和函数作用域,而在Nodejs中也自己的作用域,分为全局作用域(global)和模块作用域. js作用域: 以前学js的时候我们的全局对象是window,如: var a = 10 ...

  9. KlayGE 4.4中渲染的改进(二):DR的其他改进

    转载请注明出处为KlayGE游戏引擎,本文的永久链接为http://www.klayge.org/?p=2749   上一篇讲了TBDR的实现,本篇继续讲解deferred rendering层的一些 ...

  10. MemCache分布式缓存的一个bug

    Memcached分布式缓存策略不是由服务器端至支持的,多台服务器之间并不知道彼此的存在.分布式的实现是由客户端代码(Memcached.ClientLibrary)通过缓存key-server映射来 ...