英文:
Go with tcpdump as external command: how to close external command properly?
问题
我有一个用于在 macOS 上使用 tcpdump(外部命令)捕获网络流量的 Go 函数:
func start_tcpdump() {
    // 使用参数运行 tcpdump
    cmd := exec.Command("tcpdump", "-I", "-i", "en1", "-w", "capture.pcap")
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }
    timer := time.AfterFunc(3 * time.Second, func() {
        cmd.Process.Kill()
    })
    err := cmd.Wait()
    if err != nil{
        log.Fatal(err)
    }
    timer.Stop()
}
当这个函数完成工作后,我尝试在 Wireshark 中打开输出的 .pcap 文件,但出现以下错误:
"捕获文件似乎在一个数据包中间被截断。
可能是因为 cmd.Process.Kill() 中断了正确关闭 .pcap 文件的过程。
如何解决这个问题,以便"正确"关闭 tcpdump 外部进程?
英文:
I have a Go function to capture network traffic with <b>tcpdumb</b> (external command) on macOS:
func start_tcpdump() {
    // Run tcpdump with parameters
    cmd := exec.Command("tcpdump", "-I", "-i", "en1", "-w", "capture.pcap")
    if err := cmd.Start(); err != nil {
	    log.Fatal(err)
    }
    timer := time.AfterFunc(3 * time.Second, func() {
	    cmd.Process.Kill()
    })
    err := cmd.Wait()
    if err != nil{
	    log.Fatal(err)
    }
    timer.Stop()
}
When this function complete work, I'm trying to open output .pcap file in Wireshark and getting this error:
"<b>The capture file appears to have been cut short in the middle of a packet.</b>"<br>
Probably, <i>cmd.Process.Kill()</i> interrupts correct closing of .pcap-file.
What solution could be applied for "proper" closing of tcpdumb external process?
答案1
得分: 3
你应该使用cmd.Process.signal(os.Interrupt)来发送信号给tcpdump退出,Kill()内部调用的是signal(Kill),相当于使用kill -9强制进程退出。
英文:
You should use cmd.Process.signal(os.Interrupt) to signal tcpdump to exit, Kill() internally calls signal(Kill) which is equivalent to kill -9 to force the process to exit.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论