如何終止用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. docker-compose 為何找不到配置文件?2. ddos - apache日志很多其它網址,什么情況?3. 請問一下各位老鳥 我一直在學習獨孤九賤 現在是在tp5 今天發現 這個系列視頻沒有實戰4. android - E/dalvikvm: Could not find class java.nio.file.Path,5. boot2docker無法啟動6. python是怎么實現過濾 #注釋代碼的?7. javascript - 前端開發 本地靜態文件頻繁修改,預覽時的緩存怎么解決?8. mysql數據庫每次查詢是一條線程嗎?9. python - linux怎么在每天的凌晨2點執行一次這個log.py文件10. 使用uuid,并不能利用mysql的索引,有什么解決辦法?
