python主线程主动杀死子线程_Python-不能用KeyboardInterrup杀死主线程

我在做一个简单的多线程端口扫描器。它扫描主机上的所有端口并返回打开的端口。问题是中断了扫描。扫描需要很长时间才能完成,有时我想在扫描过程中用C-C终止程序。问题是扫描不会停止。主线程被锁在queue.join()上,并且不受键盘中断的影响,直到队列中的所有数据都被处理完毕,这样主线程就会被解除锁并优雅地退出程序。我所有的线程都是守护的,所以当主线程死了,它们应该和他一起死。

我试过用信号库,没有成功。重写线程。线程类和为正常终止添加方法不起作用。。。主线程在执行queue.join()时不会接收键盘中断import threading, sys, Queue, socket

queue = Queue.Queue()

def scan(host):

while True:

port = queue.get()

if port > 999 and port % 1000 == 0:

print port

try:

#sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#sock.settimeout(2) #you need timeout or else it will try to connect forever!

#sock.connect((host, port))

#----OR----

sock = socket.create_connection((host, port), timeout = 2)

sock.send('aaa')

data = sock.recv(100)

print "Port {} open, message: {}".format(port, data)

sock.shutdown()

sock.close()

queue.task_done()

except:

queue.task_done()

def main(host):

#populate queue

for i in range(1, 65536):

queue.put(i)

#spawn worker threads

for port in range(100):

t = threading.Thread(target = scan, args = (host,))

t.daemon = True

t.start()

if __name__ == '__main__':

host = ""

#does input exist?

try:

host = sys.argv[1]

except:

print "No argument was recivied!"

exit(1)

#is input sane?

try:

host = socket.gethostbyname(host)

except:

print "Adress does not exist"

exit(2)

#execute main program and wait for scan to complete

main(host)

print "Post main() call!"

try:

queue.join()

except keyboardInterrupt:

print "C-C"

exit(3)

编辑:

我用时间模块找到了一个解决方案。#execute main program and wait for scan to complete

main(host)

#a little trick. queue.join() makes main thread immune to keyboardinterrupt. So use queue.empty() with time.sleep()

#queue.empty() is "unreliable" so it may return True a bit earlier then intented.

#when queue is true, queue.join() is executed, to confirm that all data was processed.

#not a true solution, you can't interrupt main thread near the end of scan (when queue.empty() returns True)

try:

while True:

if queue.empty() == False:

time.sleep(1)

else:

break

except KeyboardInterrupt:

print "Alas poor port scanner..."

exit(1)

queue.join()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值