子进程中带有 tcpdump 的 Python:如何正确关闭子进程?
我有一个 Python 脚本,用于在 subprocess
中使用 tcpdump
捕获网络流量:
I have a Python script to capture network traffic with tcpdump
in a subprocess
:
p = subprocess.Popen(['tcpdump', '-I', '-i', 'en1',
'-w', 'cap.pcap'], stdout=subprocess.PIPE)
time.sleep(10)
p.kill()
当这个脚本完成它的工作时,我试图在 Wireshark 中打开输出 .pcap
文件并得到这个 错误:
When this script completes its work, I'm trying to open output .pcap
file in Wireshark and getting this error:
捕获文件似乎在数据包中间被剪短了."
"The capture file appears to have been cut short in the middle of a packet."
什么解决方案可以应用于正确"关闭tcpdump
的subprocess
?
What solution could be applied for "proper" closing of tcpdump
's subprocess
?
代替 p.kill()
,你可以使用 p.send_signal(subprocess.signal.SIGTERM)
code> 发送终止信号而不是终止信号(p.terminate()
也是如此).
Instead of p.kill()
, you can use p.send_signal(subprocess.signal.SIGTERM)
to send a terminate signal rather than a kill (p.terminate()
does the same).
Popen 文档 描述了 send_signal()
命令.关于信号的文档有点薄弱,但 dir(subprocess.signal) 将列出您可能发送给进程的所有信号,但终止应该允许它一些时间来清理.
The Popen docs describe the send_signal()
command. The documentation on signals is a bit weak, but a dir(subprocess.signal) will list all the signals you may send to the process, but terminate should allow it some time to clean up.