Segfault while trying to keep busy main loop

To test my understanding of other Gtk bits, I would like to write a program that always has an event ready for the main loop to consume. I wrote this short program to try:

#include <gtk/gtk.h> static void toggle(GtkWidget *check, gpointer data) { gboolean checked; g_object_get(check, "active", &checked, NULL); g_object_set(check, "active", !checked, NULL); } int main(int argc, char *argv[]) { GtkWidget *window, *check; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); check = gtk_check_button_new(); g_signal_connect(check, "toggled", G_CALLBACK(toggle), NULL); gtk_container_add(GTK_CONTAINER(window), check); gtk_widget_show_all(window); gtk_main(); } 

When I run this program and check the box, it turns off. What gives? What is the right way to keep the main loop busy?

(Lateral note: it reliably switches 2048 times before segfault - a suspiciously round number.)

+6
source share
1 answer

In your toggle handler, you set checked , which causes the toggle signal to be issued, which calls the handler again ...

 #11564 0xb775ba50 in g_closure_invoke () from /usr/lib/libgobject-2.0.so.0 #11565 0xb776e5d0 in ?? () from /usr/lib/libgobject-2.0.so.0 #11566 0xb77774d6 in g_signal_emit_valist () from /usr/lib/libgobject-2.0.so.0 #11567 0xb7777682 in g_signal_emit () from /usr/lib/libgobject-2.0.so.0 #11568 0xb7e067ba in gtk_toggle_button_toggled () 

I did not follow him, but I see how> 11000 frames will lead to segfault.

To answer your other question: I think that the way to save the full full loop would be with g_idle_add() :

 #include <gtk/gtk.h> static void toggle(GtkWidget *check, gpointer data) { g_print("."); } GtkWidget *window, *check; static gboolean toggle_it() { gboolean checked; g_object_get(check, "active", &checked, NULL); g_object_set(check, "active", !checked, NULL); return TRUE; } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); check = gtk_check_button_new(); g_signal_connect(check, "toggled", G_CALLBACK(toggle), NULL); gtk_container_add(GTK_CONTAINER(window), check); gtk_widget_show_all(window); g_idle_add((GSourceFunc)toggle_it, NULL); gtk_main(); } 
+7
source

Source: https://habr.com/ru/post/917223/


All Articles