2023-10-25
The following code creates a callback that calls a function every second and prints the current time:
C#include <glib.h> // // Callback for printing current time // gboolean timeout_callback (gpointer data) { // // Initialize current time // GDateTime *time; { time = g_date_time_new_now (g_time_zone_new_local ()); if (time == NULL) { return FALSE; } } // // Print current time // { g_print ("Current time: %02d:%02d:%02d\n", g_date_time_get_hour (time), g_date_time_get_minute (time), g_date_time_get_second (time)); } return TRUE; } // // main function // int main () { // // Initialize main loop // GMainLoop *loop; { loop = g_main_loop_new (NULL, FALSE); } // // Add callback to perform every second // { g_timeout_add (1000, timeout_callback, loop); } // // Start main loop // { g_print ("Starting main loop (CTRL+C to quit) ...\n"); g_main_loop_run (loop); } // // End main loop // { g_main_loop_unref (loop); } }
Shellcc `pkg-config --cflags glib-2.0` main.c `pkg-config --libs glib-2.0`
Shell./a.out
Starting main loop (CTRL+C to quit) ...
Current time: 21:19:17
Current time: 21:19:18
Current time: 21:19:19
Current time: 21:19:20
Current time: 21:19:21
^C
Press CTRL+C
to end program.