How do I create a new thread to make pcap_loop() and gtk_main() compatible?

感情迁移 提交于 2019-12-06 00:35:25

Unless I am missing something, your problem is that both GTK+ and libpcap are organized around events fired from a main loop. Without looking through the documentation, I don't know about GTK+, but there is another mode of operation for libpcap: You can use pcap_next() or pcap_next_ex() without giving up control over your program flow.

It should be possible to register a function that periodically calls one of these two functions using g_timeout_add() or g_idle_add(), removing the need to mess around with threads and mutex mechanisms altogether.

Take a look at the documentation for g_thread_create(). Also read this tutorial and this blog post for more information on multithreaded GTK programs.

Basically you'll want to call gtk_main() first when you've built your user interface and started your program. Then in the callback for the "start" button, create a new thread with g_thread_create() in which you call pcap_loop().

The "stop" button is a little more difficult since GLib doesn't allow you to interrupt a thread from a different thread. You'll have to create some signaling mechanism; for example, a boolean abort flag protected by a GMutex. In your stop button callback, lock the flag with g_mutex_lock(), set it, and unlock it with g_mutex_unlock(). In your packet_handler, also lock the flag, read it, and unlock it. If the flag was set, then call whatever it is you call to make pcap break out of the loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!