2014-09-01 2 views
2

두 개의 스레드에서 실행되는 간단한 Python 응용 프로그램이 있습니다. 하나는 SMTP 서버이고 다른 하나는 HTTP 서버입니다. 터미널에서 시작할 때 Ctrl + C에 반응하지 않습니다. 뭔가가, 그 serve_forever() 전화 잘못 될 수 어쩌면 스레드 또는 뭔가 잘 재생되지 않는 것으로 의심Threaded Python 응용 프로그램이 Ctrl + C로 반응하지 않습니다

import asyncore 
import threading 
import SimpleHTTPServer 
import SocketServer 

from smtpd import SMTPServer 


class MailHoleSMTP(SMTPServer): 
    def process_message(self, peer, mailfrom, rcpttos, data): 
     pass 


def run_smtp(): 
    MailHoleSMTP(('localhost', 1025), None) 
    asyncore.loop() 


def run_http(): 
    handler = SimpleHTTPServer.SimpleHTTPRequestHandler 
    httpd = SocketServer.TCPServer(('localhost', 1080), handler) 
    httpd.serve_forever() 


if __name__ == '__main__': 
    http_thread = threading.Thread(target=run_http) 
    smtp_thread = threading.Thread(target=run_smtp) 
    http_thread.start() 
    smtp_thread.start() 

    http_thread.join() 
    smtp_thread.join() 

: 다음은 코드입니다. Ctrl + C로 반응하도록하려면 어떻게해야합니까?

UPD : 두 스레드 중 하나만 실행하더라도 (두 스레드 모두) 작동하지 않습니다.

+0

출력물을 볼 수 있습니까? 추적 가능성이 있습니까? – Messa

+0

아니, 그냥^C^C^C^C^C^C^C^C :) –

+0

3 개의 thread가 아니라. 2. 키보드를 잡는 * main * thread를 세지 않고있다. 일시 정지. –

답변

3

그래서 여기에서 해결해야 할 두 가지 문제가 있습니다. 첫째, join 스레드는 어떤 신호에도 응답하지 않습니다.

while http_thread.is_alive(): 
    http_thread.join(1) 
#similar for smtp_thread 

이 프로그램이 KeyboardInterrupt 신호에 반응 할 것이다, 그러나 지금은 모든 일이 완전히 종료되지 않는 것을 알 수 있습니다 : 매초마다 신호를 확인하기 위해 반복하여 해당 수정. 이유는 신호가 다른 스레드로 전파되지 않기 때문에 작업자 스레드가 완료 될 때까지 전체 프로세스가 종료되지 않기 때문입니다 (비 데몬이기 때문에). 해결하려면 가장 간단한 방법은 그들에게 데몬 스레드를 만드는 것입니다 :

http_thread = threading.Thread(target=run_http) 
http_thread.daemon = True 
smtp_thread = threading.Thread(target=run_smtp) 
smtp_thread.daemon = True 
... 

신호는 다중 스레드 응용 프로그램에서 매우 일반적인 주제입니다, 그래서 당신은 do more reading 할 수 있습니다.

+0

아쉽게도 작동하지 않습니다. –

+0

나는 이것을 시도했지만'thread.join()'이 신호 처리를 차단하는 것으로 보인다. 하지만 thread.is_alive() : time.sleep (1)'로 바꾸십시오. - 저에게 맞습니다. – Messa

+0

아 맞아. 오늘 더 많은 커피가 필요합니다 :-) – roippi

관련 문제