如何终止用python写的socket服务端程序?
问题描述
用python写了一个socket服务端的程序,但是启动之后由于监听连接的是一个死循环,所以不知道怎样在cmd运行程序的时候将其终止。
#!/usr/bin/python# -*- coding: utf-8 -*-import socketimport threading, timedef tcplink(sock,addr): print(’Accept new connection from %s:%s...’ %addr) sock.send(b’Welcome!’) while True:data=sock.recv(1024)time.sleep(1)if not data or data.decode(’utf-8’)==’exit’: breaksock.send((’Hello,%s!’% data.decode(’utf-8’)).encode(’utf-8’)) sock.close() print(’Connection from %s:%s closed.’ % addr) s=socket.socket()s.bind((’127.0.0.1’,1234))s.listen(5)print(’Waiting for conection...’)while True: #accept a new connection sock,addr=s.accept() #create a new thread t=threading.Thread(target=tcplink,args=(sock,addr)) t.start()
在win10上的cmd运行后的情况是按ctrl+c,ctrl+z,ctrl+d都不能终止,请问要怎么终止程序?
问题解答
回答1:Ctrl + C
回答2:在启动线程之前,添加 setDaemon(True)
while True: #accept a new connection sock,addr=s.accept() #create a new thread t=threading.Thread(target=tcplink,args=(sock,addr)) t.setDaemon(True) # <-- add this t.start()
daemon
A boolean value indicating whether this thread is a daemonthread (True) or not (False). This must be set before start() iscalled, otherwise RuntimeError is raised. Its initial value isinherited from the creating thread; the main thread is not a daemonthread and therefore all threads created in the main thread default todaemon = False.
The entire Python program exits when no alive non-daemon threads areleft.
这样 <C-c> 的中断信号就会被 rasie。
回答3:kill -9回答4:
关闭cmd命令窗口,重新开启一个cmd,我是这么做的。
回答5:可以使用signal模块,当按住Ctrl+C时,捕捉信息,然后退出.
#!/usr/bin/env python# -*- coding: utf-8 -*-import signaldef do_exit(signum, frame): print('exit ...') exit()signal.signal(signal.SIGINT, do_exit)while True: print('processing ...')回答6:
我记得可以
try: ......except KeyboardInterrupt: exit()
相关文章:
1. 怎样用python给mp3添加封面?2. linux - 【已解决】fabric部署的Python项目Apache启动之后提示403Forbidden该如何解决?3. 上传多图时,最后一张图为缩略图,想设置第一张图为缩略图怎么解决?4. python - 如何获取rabbitmq连接的celery的个数5. js怎样实现在类似qq的联系人分组中进行搜索后,又可恢复原分组的界面?6. python 中文乱码问题7. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。8. javascript - 百度地图一开始设置了中心点,怎么通过按钮在调转到对应的中心点????9. mysql优化 - mysql 一张表如果不能确保字段列长度一致,是不是就不需要用到char。10. python - 如何将文本文件的CR换行符换成LF换行符?