在同一程序中运行两个阻塞循环

0 投票
1 回答
838 浏览
提问于 2025-04-18 12:49

我想在同一个程序里运行两个阻塞循环。
在我的程序中,我使用nfqueue来拦截数据包。当队列创建后,它就开始等待数据包,这会让程序停下来不动。当有数据包到达时,它会调用cb()函数,然后再开始监听新的数据包。

这是我的程序:

import nfqueue, socket
from scapy.all import *
import os

os.system('iptables -t mangle -A PREROUTING -j NFQUEUE --queue-num 1')
os.system('iptables -t mangle -A POSTROUTING -j NFQUEUE --queue-num 2')


count = 0

def cb(payload):
    global count
    count +=1
    data = payload.get_data()
    p = IP(data) 

    print str(count) + ": TOS     = " + str(p.tos)
    payload.set_verdict(nfqueue.NF_ACCEPT)


def run_queue(queue_num):
    print "Preparing the queue"
    q = nfqueue.queue()
    q.open()
    q.unbind(socket.AF_INET)
    q.bind(socket.AF_INET)
    q.set_callback(cb)
    q.create_queue(queue_num)

    try:
        print "Running the queue"
        q.try_run()

    except KeyboardInterrupt, e:
        print "interruption"
        q.unbind(socket.AF_INET)
        q.close()


run_queue(1)
run_queue(2)

我该如何在同一个程序中运行两个或更多这样的阻塞循环呢?

任何帮助都非常感谢。
谢谢!

1 个回答

1

你可以让每个循环在自己的线程中运行,像这样:

import nfqueue, socket
from threading import Thread
from scapy.all import *
import os

os.system('iptables -t mangle -A PREROUTING -j NFQUEUE --queue-num 1')
os.system('iptables -t mangle -A POSTROUTING -j NFQUEUE --queue-num 2')


count = 0

def cb(payload):
    global count
    count +=1
    data = payload.get_data()
    p = IP(data) 

    print str(count) + ": TOS     = " + str(p.tos)
    payload.set_verdict(nfqueue.NF_ACCEPT)


def run_queue(queue_num):
    print "Preparing the queue"
    q = nfqueue.queue()
    q.open()
    q.unbind(socket.AF_INET)
    q.bind(socket.AF_INET)
    q.set_callback(cb)
    q.create_queue(queue_num)

    try:
        print "Running the queue"
        q.try_run()

    except KeyboardInterrupt, e:
        print "interruption"
        q.unbind(socket.AF_INET)
        q.close()

if __name__ == "__main__":
    t1 = Thread(target=run_queue, args=(1,))
    t1.start()
    t2 = Thread(target=run_queue, args=(2,))
    t2.start()
    t1.join()
    t2.join()

撰写回答