子进程中带有 tcpdump 的 Python:如何正确关闭子进程? [英] Python with tcpdump in a subprocess: how to close subprocess properly?

查看:78
本文介绍了子进程中带有 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."

什么解决方案可以应用于正确"关闭tcpdumpsubprocess?

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.

这篇关于子进程中带有 tcpdump 的 Python:如何正确关闭子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆