pythonstart&;通过线程停止长时间运行的程序
我的环境是Python+Linux 我有一个可以从命令行运行的程序。运行后,当用户按ctrl+c时,它会将一些数据保存在输出文件中(在我的情况下,该程序会在用户按ctrl+c后将嗅探到的数据包存储在pcap文件中)。没有ctrl+c,程序不会退出/停止 我必须通过线程运行这个程序tcpdump,在一些操作之后,我必须停止线程并收集pcap文件 我的代码:pythonstart&;通过线程停止长时间运行的程序,python,multithreading,Python,Multithreading,我的环境是Python+Linux 我有一个可以从命令行运行的程序。运行后,当用户按ctrl+c时,它会将一些数据保存在输出文件中(在我的情况下,该程序会在用户按ctrl+c后将嗅探到的数据包存储在pcap文件中)。没有ctrl+c,程序不会退出/停止 我必须通过线程运行这个程序tcpdump,在一些操作之后,我必须停止线程并收集pcap文件 我的代码: class MyClass(threading.Thread): def __init__(self): thread
class MyClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.process = None
self.stdout = None
self.stderr = None
def run(self):
print '[+] Starting Sniffer at : ',Interface
cmd = 'tcpdump -i lo tcp port 8080 -w hello.pcap'
p = subprocess.Popen(cmd.split(),shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
def stop(self):
print "[+] Trying to stop the sniffer thread.."
if self.process is not None:
self.process.terminate()
self.process = None
print '[+] Thread stopped'
s = MyClass()
s.start()
#some operation
s.stop()
# some opes
我面临的问题是我得到了空的pcap文件。我想可能是因为以下问题之一,它正在发生
谢谢,您必须以正常方式妖魔化您的脚本。试着这样做:“空”文件可能是因为缓冲。调用file对象上的
flush()
,或close()
它。我认为Ctrl+C将终止程序,您是否在应用程序中捕获它并适当停止?另外,您是否以root用户身份运行脚本?您必须以正常方式妖魔化脚本。试着这样做:“空”文件可能是因为缓冲。调用file对象上的flush()
,或close()
它。我认为Ctrl+C将终止程序,您是否在应用程序中捕获它并适当停止?另外,您是否以root用户身份运行脚本?