622   Linux Python

Linux信号,可以理解为中断信号,作为进程之间的通信使用
比如一个进程在后台运行,通过kill命令传递终止信号到进程中,让进程自动终止,并在终止前做一些保存数据或者清理缓存的事情

python通过signal模块实现了Linux信号处理功能,下面来看看如何实现

1,不使用信号的代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import signal
import time
class testSignal():
	def __init__(self,input):
		print '__init__: %s' % input

	def main(self):
		self.flag = True
		i = 0
		print ''
		print 'start ok'
		print 'start to do something'
		print ''
		while self.flag:
			i = i + 1
			print 'date: %s' % time.strftime('%Y-%m-%d %H:%M:%S')
			print 'time: %s' % i
			time.sleep(2)

		print ''
		print 'something to do before stop'
		print 'stop ok'
		print ''

if __name__ == '__main__':

	try:
		input = 'testSignal'
		testSignal = testSignal(input)
		
	except Exception, e:
		print "__main__: %s" % str(e)
		testSignal = None

	if testSignal != None:
		testSignal.main()

执行该文件,然后在键盘ctrl+c退出,效果如下

[root@localhost test]# ./test.py 
__init__: testSignal

start ok
start to do something

date: 2016-09-10 03:10:10
time: 1
date: 2016-09-10 03:10:12
time: 2
^CTraceback (most recent call last):
  File "./test.py", line 53, in 
    testSignal.main()
  File "./test.py", line 23, in main
    time.sleep(2)
KeyboardInterrupt

直接就退出了程序,并没有执行while后面print的输出内容,即没有在终止进程前按顺序执行完整

 

 

2,使用信号的代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import signal
import time


class testSignal():
	def __init__(self,input):
		print '__init__: %s' % input

	def main(self):
		self.flag = True
		i = 0
		print ''
		print 'start ok'
		print 'start to do something'
		print ''
		while self.flag:
			i = i + 1
			print 'date: %s' % time.strftime('%Y-%m-%d %H:%M:%S')
			print 'time: %s' % i
			time.sleep(2)

		print ''
		print 'something to do before stop'
		print 'stop ok'
		print ''



if __name__ == '__main__':

	try:
		input = 'testSignal'
		testSignal = testSignal(input)

		def handler(signal, frame):
			testSignal.flag = False
			print ''
			print 'signal: %s' % signal
			print ''

		signal.signal(signal.SIGINT, handler)

	except Exception, e:
		print "__main__: %s" % str(e)
		testSignal = None

	if testSignal != None:
		testSignal.main()
        

执行该文件,然后在键盘ctrl+c退出,效果如下

[root@localhost test]# ./test.py 
__init__: testSignal

start ok
start to do something

date: 2016-09-10 03:14:38
time: 1
date: 2016-09-10 03:14:40
time: 2
^C
signal: 2


something to do before stop
stop ok

[root@localhost test]# 

看到没有,输出了 something to do before stop ,即在终止进程前按顺序执行完整,这就是使用信号的好处。
通过信号,我们可以在终止进程前,执行一些必要的操作,比如保存数据,情况缓存等,当然也可以忽略这些信号。
有兴趣的就自己深入了解Linux信号吧,这里点到即止。




Leave a Reply

Your email address will not be published. Required fields are marked *