簡體   English   中英

Python-多線程:分段錯誤

[英]Python-mutithreading:Segmentation fault

有時候運行這個程序會提示Segmentation fault

start sniffing
Fatal Python error: Segmentation fault

Thread 0x00007f5e3bfff700 (most recent call first):
  File "/usr/local/lib/python3.8/dist-packages/iptc/ip4tc.py", line 1610 in commit
  File "/usr/local/lib/python3.8/bin/python-sudo.sh: line 2:  3087 Segmentation fault      sudo /usr/bin/python3 "$@"

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

我的代碼:

table = iptc.Table(iptc.Table.FILTER)
chain = iptc.Chain(table, "INPUT")


def Callback(packet):
    if packet[IP].proto == 17:
        if packet[UDP].dport == 62201:
            sp = packet[IP].src
            thread_add = threading.Thread(target=add_rules, args=(sp, ))
            thread_add.start()


def add_rules(sp):
    global chain, table
    
    rule = iptc.Rule()
    rule.src = sp
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target

    chain.insert_rule(rule)
    print('rule ' + sp + ' insert! {}'.format(time.time()))
    time.sleep(30)
    chain.delete_rule(rule)
    print('time out delete ' + sp + ' this rule! {}'.format(time.time()))           
        
  
while 1:
    # 使用sniff抓包
    print('start sniffing')
    msg = sniff(filter='dst port 62201', prn=Callback)
    time.sleep(0.03)

server.close()
print('Sever closed')

可能的原因與您正在使用的庫或您使用它的方式有關。 有一個明顯的危險:您使用多個線程在同一個鏈和表上工作,但沒有使用互斥鎖來保護對它們的訪問。

嘗試這樣的事情:

table = iptc.Table(iptc.Table.FILTER)
chain = iptc.Chain(table, "INPUT")
mutex = threading.Lock()

def add_rules(sp):
    with mutex:
        rule = iptc.Rule()
        rule.src = sp
        target = iptc.Target(rule, "ACCEPT")
        rule.target = target
        chain.insert_rule(rule)
    print('rule ' + sp + ' insert! {}'.format(time.time()))
    time.sleep(30)
    with mutex:
        chain.delete_rule(rule)
    print('time out delete ' + sp + ' this rule! {}'.format(time.time()))  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM