1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * SPDX-License-Identifier: LGPL-2.1-or-later
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
36 #include "glib_trace.h"
38 /* Uncomment the next line (and the corresponding line in gpoll.c) to
39 * enable debugging printouts if the environment variable
40 * G_MAIN_POLL_DEBUG is set to some value.
42 /* #define G_MAIN_POLL_DEBUG */
45 /* Always enable debugging printout on Windows, as it is more often
48 #define G_MAIN_POLL_DEBUG
52 #include "glib-unix.h"
55 #include <sys/eventfd.h>
60 #include <sys/types.h>
63 #ifdef HAVE_SYS_TIME_H
65 #endif /* HAVE_SYS_TIME_H */
68 #endif /* G_OS_UNIX */
73 #include <sys/syscall.h>
75 #include <linux/wait.h> /* P_PIDFD */
77 #define W_EXITCODE(ret, sig) ((ret) << 8 | (sig))
80 #define W_STOPCODE(sig) ((sig) << 8 | 0x7f)
83 /* musl doesn’t define WCOREFLAG while glibc does. Unfortunately, there’s no way
84 * to detect we’re building against musl, so just define it and hope.
85 * See https://git.musl-libc.org/cgit/musl/tree/include/sys/wait.h#n51 */
86 #define WCOREFLAG 0x80
89 /* Same as above, for musl */
90 #define __W_CONTINUED 0xffff
92 #endif /* HAVE_PIDFD */
97 #endif /* G_OS_WIN32 */
99 #ifdef HAVE_MACH_MACH_TIME_H
100 #include <mach/mach_time.h>
103 #include "glib_trace.h"
108 #include "giochannel.h"
112 #include "gstrfuncs.h"
113 #include "gtestutils.h"
114 #include "gthreadprivate.h"
115 #include "gtrace-private.h"
121 #ifdef G_MAIN_POLL_DEBUG
126 #include "gmain-internal.h"
127 #include "glib-init.h"
128 #include "glib-private.h"
132 * @title: The Main Event Loop
133 * @short_description: manages all available sources of events
135 * The main event loop manages all the available sources of events for
136 * GLib and GTK applications. These events can come from any number of
137 * different types of sources such as file descriptors (plain files,
138 * pipes or sockets) and timeouts. New types of event sources can also
139 * be added using g_source_attach().
141 * To allow multiple independent sets of sources to be handled in
142 * different threads, each source is associated with a #GMainContext.
143 * A #GMainContext can only be running in a single thread, but
144 * sources can be added to it and removed from it from other threads. All
145 * functions which operate on a #GMainContext or a built-in #GSource are
148 * Each event source is assigned a priority. The default priority,
149 * %G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
150 * Values greater than 0 denote lower priorities. Events from high priority
151 * sources are always processed before events from lower priority sources: if
152 * several sources are ready to dispatch, the ones with equal-highest priority
153 * will be dispatched on the current #GMainContext iteration, and the rest wait
154 * until a subsequent #GMainContext iteration when they have the highest
155 * priority of the sources which are ready for dispatch.
157 * Idle functions can also be added, and assigned a priority. These will
158 * be run whenever no events with a higher priority are ready to be dispatched.
160 * The #GMainLoop data type represents a main event loop. A GMainLoop is
161 * created with g_main_loop_new(). After adding the initial event sources,
162 * g_main_loop_run() is called. This continuously checks for new events from
163 * each of the event sources and dispatches them. Finally, the processing of
164 * an event from one of the sources leads to a call to g_main_loop_quit() to
165 * exit the main loop, and g_main_loop_run() returns.
167 * It is possible to create new instances of #GMainLoop recursively.
168 * This is often used in GTK applications when showing modal dialog
169 * boxes. Note that event sources are associated with a particular
170 * #GMainContext, and will be checked and dispatched for all main
171 * loops associated with that GMainContext.
173 * GTK contains wrappers of some of these functions, e.g. gtk_main(),
174 * gtk_main_quit() and gtk_events_pending().
176 * ## Creating new source types
178 * One of the unusual features of the #GMainLoop functionality
179 * is that new types of event source can be created and used in
180 * addition to the builtin type of event source. A new event source
181 * type is used for handling GDK events. A new source type is created
182 * by "deriving" from the #GSource structure. The derived type of
183 * source is represented by a structure that has the #GSource structure
184 * as a first element, and other elements specific to the new source
185 * type. To create an instance of the new source type, call
186 * g_source_new() passing in the size of the derived structure and
187 * a table of functions. These #GSourceFuncs determine the behavior of
188 * the new source type.
190 * New source types basically interact with the main context
191 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
192 * to determine the maximum amount of time that the main loop will sleep
193 * before checking the source again. In addition, or as well, the source
194 * can add file descriptors to the set that the main context checks using
195 * g_source_add_poll().
197 * ## Customizing the main loop iteration
199 * Single iterations of a #GMainContext can be run with
200 * g_main_context_iteration(). In some cases, more detailed control
201 * of exactly how the details of the main loop work is desired, for
202 * instance, when integrating the #GMainLoop with an external main loop.
203 * In such cases, you can call the component functions of
204 * g_main_context_iteration() directly. These functions are
205 * g_main_context_prepare(), g_main_context_query(),
206 * g_main_context_check() and g_main_context_dispatch().
208 * If the event loop thread releases #GMainContext ownership until the results
209 * required by g_main_context_check() are ready you must create a context with
210 * the flag %G_MAIN_CONTEXT_FLAGS_OWNERLESS_POLLING or else you'll lose
211 * g_source_attach() notifications. This happens for instance when you integrate
212 * the GLib event loop into implementations that follow the proactor pattern
213 * (i.e. in these contexts the `poll()` implementation will reclaim the thread for
214 * other tasks until the results are ready). One example of the proactor pattern
215 * is the Boost.Asio library.
217 * ## State of a Main Context # {#mainloop-states}
219 * The operation of these functions can best be seen in terms
220 * of a state diagram, as shown in this image.
222 * ![](mainloop-states.gif)
224 * On UNIX, the GLib mainloop is incompatible with fork(). Any program
225 * using the mainloop must either exec() or exit() from the child
226 * without returning to the mainloop.
228 * ## Memory management of sources # {#mainloop-memory-management}
230 * There are two options for memory management of the user data passed to a
231 * #GSource to be passed to its callback on invocation. This data is provided
232 * in calls to g_timeout_add(), g_timeout_add_full(), g_idle_add(), etc. and
233 * more generally, using g_source_set_callback(). This data is typically an
234 * object which ‘owns’ the timeout or idle callback, such as a widget or a
235 * network protocol implementation. In many cases, it is an error for the
236 * callback to be invoked after this owning object has been destroyed, as that
237 * results in use of freed memory.
239 * The first, and preferred, option is to store the source ID returned by
240 * functions such as g_timeout_add() or g_source_attach(), and explicitly
241 * remove that source from the main context using g_source_remove() when the
242 * owning object is finalized. This ensures that the callback can only be
243 * invoked while the object is still alive.
245 * The second option is to hold a strong reference to the object in the
246 * callback, and to release it in the callback’s #GDestroyNotify. This ensures
247 * that the object is kept alive until after the source is finalized, which is
248 * guaranteed to be after it is invoked for the final time. The #GDestroyNotify
249 * is another callback passed to the ‘full’ variants of #GSource functions (for
250 * example, g_timeout_add_full()). It is called when the source is finalized,
251 * and is designed for releasing references like this.
253 * One important caveat of this second approach is that it will keep the object
254 * alive indefinitely if the main loop is stopped before the #GSource is
255 * invoked, which may be undesirable.
260 typedef struct _GIdleSource GIdleSource;
261 typedef struct _GTimeoutSource GTimeoutSource;
262 typedef struct _GChildWatchSource GChildWatchSource;
263 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
264 typedef struct _GPollRec GPollRec;
265 typedef struct _GSourceCallback GSourceCallback;
269 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
270 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
271 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
274 typedef struct _GSourceList GSourceList;
278 GSource *head, *tail;
282 typedef struct _GMainWaiter GMainWaiter;
290 typedef struct _GMainDispatch GMainDispatch;
292 struct _GMainDispatch
298 #ifdef G_MAIN_POLL_DEBUG
299 gboolean _g_main_poll_debug = FALSE;
304 /* The following lock is used for both the list of sources
305 * and the list of poll records
311 GMainContextFlags flags;
314 gint ref_count; /* (atomic) */
316 GHashTable *sources; /* guint -> GSource */
318 GPtrArray *pending_dispatches;
319 gint timeout; /* Timeout for current iteration */
323 gint in_check_or_prepare;
325 GPollRec *poll_records;
326 guint n_poll_records;
327 GPollFD *cached_poll_array;
328 guint cached_poll_array_size;
334 /* Flag indicating whether the set of fd's changed during a poll */
335 gboolean poll_changed;
340 gboolean time_is_fresh;
343 struct _GSourceCallback
345 gint ref_count; /* (atomic) */
348 GDestroyNotify notify;
353 GMainContext *context;
354 gboolean is_running; /* (atomic) */
355 gint ref_count; /* (atomic) */
364 struct _GTimeoutSource
367 /* Measured in seconds if 'seconds' is TRUE, or milliseconds otherwise. */
373 struct _GChildWatchSource
377 /* @poll is always used on Windows.
378 * On Unix, poll.fd will be negative if PIDFD is unavailable. */
381 gboolean child_maybe_exited; /* (atomic) */
382 #endif /* G_OS_WIN32 */
385 struct _GUnixSignalWatchSource
389 gboolean pending; /* (atomic) */
400 struct _GSourcePrivate
402 GSList *child_sources;
403 GSource *parent_source;
407 /* This is currently only used on UNIX, but we always declare it (and
408 * let it remain empty on Windows) to avoid #ifdef all over the place.
412 GSourceDisposeFunc dispose;
414 gboolean static_name;
417 typedef struct _GSourceIter
419 GMainContext *context;
425 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
426 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
427 #define G_THREAD_SELF g_thread_self ()
429 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
430 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
432 /* Forward declarations */
434 static void g_source_unref_internal (GSource *source,
435 GMainContext *context,
437 static void g_source_destroy_internal (GSource *source,
438 GMainContext *context,
440 static void g_source_set_priority_unlocked (GSource *source,
441 GMainContext *context,
443 static void g_child_source_remove_internal (GSource *child_source,
444 GMainContext *context);
446 static gboolean g_main_context_acquire_unlocked (GMainContext *context);
447 static void g_main_context_release_unlocked (GMainContext *context);
448 static gboolean g_main_context_prepare_unlocked (GMainContext *context,
450 static gint g_main_context_query_unlocked (GMainContext *context,
455 static gboolean g_main_context_check_unlocked (GMainContext *context,
459 static void g_main_context_dispatch_unlocked (GMainContext *context);
460 static void g_main_context_poll_unlocked (GMainContext *context,
465 static void g_main_context_add_poll_unlocked (GMainContext *context,
468 static void g_main_context_remove_poll_unlocked (GMainContext *context,
471 static void g_source_iter_init (GSourceIter *iter,
472 GMainContext *context,
473 gboolean may_modify);
474 static gboolean g_source_iter_next (GSourceIter *iter,
476 static void g_source_iter_clear (GSourceIter *iter);
478 static gboolean g_timeout_dispatch (GSource *source,
479 GSourceFunc callback,
481 static gboolean g_child_watch_prepare (GSource *source,
483 static gboolean g_child_watch_check (GSource *source);
484 static gboolean g_child_watch_dispatch (GSource *source,
485 GSourceFunc callback,
487 static void g_child_watch_finalize (GSource *source);
490 static void unref_unix_signal_handler_unlocked (int signum);
494 static void g_unix_signal_handler (int signum);
495 static gboolean g_unix_signal_watch_prepare (GSource *source,
497 static gboolean g_unix_signal_watch_check (GSource *source);
498 static gboolean g_unix_signal_watch_dispatch (GSource *source,
499 GSourceFunc callback,
501 static void g_unix_signal_watch_finalize (GSource *source);
503 static gboolean g_idle_prepare (GSource *source,
505 static gboolean g_idle_check (GSource *source);
506 static gboolean g_idle_dispatch (GSource *source,
507 GSourceFunc callback,
510 static void block_source (GSource *source);
512 static GMainContext *glib_worker_context;
517 /* UNIX signals work by marking one of these variables then waking the
518 * worker context to check on them and dispatch accordingly.
520 * Both variables must be accessed using atomic primitives, unless those atomic
521 * primitives are implemented using fallback mutexes (as those aren’t safe in
522 * an interrupt context).
524 * If using atomic primitives, the variables must be of type `int` (so they’re
525 * the right size for the atomic primitives). Otherwise, use `sig_atomic_t` if
526 * it’s available, which is guaranteed to be async-signal-safe (but it’s *not*
527 * guaranteed to be thread-safe, which is why we use atomic primitives if
530 * Typically, `sig_atomic_t` is a typedef to `int`, but that’s not the case on
531 * FreeBSD, so we can’t use it unconditionally if it’s defined.
533 #if (defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || !defined(HAVE_SIG_ATOMIC_T)
534 static volatile int unix_signal_pending[NSIG];
535 static volatile int any_unix_signal_pending;
537 static volatile sig_atomic_t unix_signal_pending[NSIG];
538 static volatile sig_atomic_t any_unix_signal_pending;
541 /* Guards all the data below */
542 G_LOCK_DEFINE_STATIC (unix_signal_lock);
543 static guint unix_signal_refcount[NSIG];
544 static GSList *unix_signal_watches;
545 static GSList *unix_child_watches;
547 GSourceFuncs g_unix_signal_funcs =
549 g_unix_signal_watch_prepare,
550 g_unix_signal_watch_check,
551 g_unix_signal_watch_dispatch,
552 g_unix_signal_watch_finalize,
555 #endif /* !G_OS_WIN32 */
556 G_LOCK_DEFINE_STATIC (main_context_list);
557 static GSList *main_context_list = NULL;
559 GSourceFuncs g_timeout_funcs =
567 GSourceFuncs g_child_watch_funcs =
569 g_child_watch_prepare,
571 g_child_watch_dispatch,
572 g_child_watch_finalize,
576 GSourceFuncs g_idle_funcs =
585 * g_main_context_ref:
586 * @context: (not nullable): a #GMainContext
588 * Increases the reference count on a #GMainContext object by one.
590 * Returns: the @context that was passed in (since 2.6)
593 g_main_context_ref (GMainContext *context)
597 g_return_val_if_fail (context != NULL, NULL);
599 old_ref_count = g_atomic_int_add (&context->ref_count, 1);
600 g_return_val_if_fail (old_ref_count > 0, NULL);
606 poll_rec_list_free (GMainContext *context,
609 g_slice_free_chain (GPollRec, list, next);
613 * g_main_context_unref:
614 * @context: (not nullable): a #GMainContext
616 * Decreases the reference count on a #GMainContext object by one. If
617 * the result is zero, free the context and free all associated memory.
620 g_main_context_unref (GMainContext *context)
625 GSList *s_iter, *remaining_sources = NULL;
629 g_return_if_fail (context != NULL);
630 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
632 if (!g_atomic_int_dec_and_test (&context->ref_count))
635 G_LOCK (main_context_list);
636 main_context_list = g_slist_remove (main_context_list, context);
637 G_UNLOCK (main_context_list);
639 /* Free pending dispatches */
640 for (i = 0; i < context->pending_dispatches->len; i++)
641 g_source_unref_internal (context->pending_dispatches->pdata[i], context, FALSE);
643 /* g_source_iter_next() assumes the context is locked. */
644 LOCK_CONTEXT (context);
646 /* First collect all remaining sources from the sources lists and store a
647 * new reference in a separate list. Also set the context of the sources
648 * to NULL so that they can't access a partially destroyed context anymore.
650 * We have to do this first so that we have a strong reference to all
651 * sources and destroying them below does not also free them, and so that
652 * none of the sources can access the context from their finalize/dispose
654 g_source_iter_init (&iter, context, FALSE);
655 while (g_source_iter_next (&iter, &source))
657 source->context = NULL;
658 remaining_sources = g_slist_prepend (remaining_sources, g_source_ref (source));
660 g_source_iter_clear (&iter);
662 /* Next destroy all sources. As we still hold a reference to all of them,
663 * this won't cause any of them to be freed yet and especially prevents any
664 * source that unrefs another source from its finalize function to be freed.
666 for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
668 source = s_iter->data;
669 g_source_destroy_internal (source, context, TRUE);
672 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
674 list = sl_iter->data;
675 g_slice_free (GSourceList, list);
677 g_list_free (context->source_lists);
679 g_hash_table_destroy (context->sources);
681 UNLOCK_CONTEXT (context);
682 g_mutex_clear (&context->mutex);
684 g_ptr_array_free (context->pending_dispatches, TRUE);
685 g_free (context->cached_poll_array);
687 poll_rec_list_free (context, context->poll_records);
689 g_wakeup_free (context->wakeup);
690 g_cond_clear (&context->cond);
694 /* And now finally get rid of our references to the sources. This will cause
695 * them to be freed unless something else still has a reference to them. Due
696 * to setting the context pointers in the sources to NULL above, this won't
697 * ever access the context or the internal linked list inside the GSource.
698 * We already removed the sources completely from the context above. */
699 for (s_iter = remaining_sources; s_iter; s_iter = s_iter->next)
701 source = s_iter->data;
702 g_source_unref_internal (source, NULL, FALSE);
704 g_slist_free (remaining_sources);
707 /* Helper function used by mainloop/overflow test.
710 g_main_context_new_with_next_id (guint next_id)
712 GMainContext *ret = g_main_context_new ();
714 ret->next_id = next_id;
720 * g_main_context_new:
722 * Creates a new #GMainContext structure.
724 * Returns: the new #GMainContext
727 g_main_context_new (void)
729 return g_main_context_new_with_flags (G_MAIN_CONTEXT_FLAGS_NONE);
733 * g_main_context_new_with_flags:
734 * @flags: a bitwise-OR combination of #GMainContextFlags flags that can only be
735 * set at creation time.
737 * Creates a new #GMainContext structure.
739 * Returns: (transfer full): the new #GMainContext
744 g_main_context_new_with_flags (GMainContextFlags flags)
746 static gsize initialised;
747 GMainContext *context;
749 if (g_once_init_enter (&initialised))
751 #ifdef G_MAIN_POLL_DEBUG
752 if (g_getenv ("G_MAIN_POLL_DEBUG") != NULL)
753 _g_main_poll_debug = TRUE;
756 g_once_init_leave (&initialised, TRUE);
759 context = g_new0 (GMainContext, 1);
761 TRACE (GLIB_MAIN_CONTEXT_NEW (context));
763 g_mutex_init (&context->mutex);
764 g_cond_init (&context->cond);
766 context->sources = g_hash_table_new (NULL, NULL);
767 context->owner = NULL;
768 context->flags = flags;
769 context->waiters = NULL;
771 context->ref_count = 1;
773 context->next_id = 1;
775 context->source_lists = NULL;
777 context->poll_func = g_poll;
779 context->cached_poll_array = NULL;
780 context->cached_poll_array_size = 0;
782 context->pending_dispatches = g_ptr_array_new ();
784 context->time_is_fresh = FALSE;
786 context->wakeup = g_wakeup_new ();
787 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
788 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
790 G_LOCK (main_context_list);
791 main_context_list = g_slist_append (main_context_list, context);
793 #ifdef G_MAIN_POLL_DEBUG
794 if (_g_main_poll_debug)
795 g_print ("created context=%p\n", context);
798 G_UNLOCK (main_context_list);
804 * g_main_context_default:
806 * Returns the global-default main context. This is the main context
807 * used for main loop functions when a main loop is not explicitly
808 * specified, and corresponds to the "main" main loop. See also
809 * g_main_context_get_thread_default().
811 * Returns: (transfer none): the global-default main context.
814 g_main_context_default (void)
816 static GMainContext *default_main_context = NULL;
818 if (g_once_init_enter (&default_main_context))
820 GMainContext *context;
822 context = g_main_context_new ();
824 TRACE (GLIB_MAIN_CONTEXT_DEFAULT (context));
826 #ifdef G_MAIN_POLL_DEBUG
827 if (_g_main_poll_debug)
828 g_print ("global-default main context=%p\n", context);
831 g_once_init_leave (&default_main_context, context);
834 return default_main_context;
838 free_context (gpointer data)
840 GMainContext *context = data;
842 TRACE (GLIB_MAIN_CONTEXT_FREE (context));
844 g_main_context_release (context);
846 g_main_context_unref (context);
850 free_context_stack (gpointer data)
852 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
855 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
858 * g_main_context_push_thread_default:
859 * @context: (nullable): a #GMainContext, or %NULL for the global-default
862 * Acquires @context and sets it as the thread-default context for the
863 * current thread. This will cause certain asynchronous operations
864 * (such as most [gio][gio]-based I/O) which are
865 * started in this thread to run under @context and deliver their
866 * results to its main loop, rather than running under the global
867 * default main context in the main thread. Note that calling this function
868 * changes the context returned by g_main_context_get_thread_default(),
869 * not the one returned by g_main_context_default(), so it does not affect
870 * the context used by functions like g_idle_add().
872 * Normally you would call this function shortly after creating a new
873 * thread, passing it a #GMainContext which will be run by a
874 * #GMainLoop in that thread, to set a new default context for all
875 * async operations in that thread. In this case you may not need to
876 * ever call g_main_context_pop_thread_default(), assuming you want the
877 * new #GMainContext to be the default for the whole lifecycle of the
880 * If you don't have control over how the new thread was created (e.g.
881 * in the new thread isn't newly created, or if the thread life
882 * cycle is managed by a #GThreadPool), it is always suggested to wrap
883 * the logic that needs to use the new #GMainContext inside a
884 * g_main_context_push_thread_default() / g_main_context_pop_thread_default()
885 * pair, otherwise threads that are re-used will end up never explicitly
886 * releasing the #GMainContext reference they hold.
888 * In some cases you may want to schedule a single operation in a
889 * non-default context, or temporarily use a non-default context in
890 * the main thread. In that case, you can wrap the call to the
891 * asynchronous operation inside a
892 * g_main_context_push_thread_default() /
893 * g_main_context_pop_thread_default() pair, but it is up to you to
894 * ensure that no other asynchronous operations accidentally get
895 * started while the non-default context is active.
897 * Beware that libraries that predate this function may not correctly
898 * handle being used from a thread with a thread-default context. Eg,
899 * see g_file_supports_thread_contexts().
904 g_main_context_push_thread_default (GMainContext *context)
907 gboolean acquired_context;
909 acquired_context = g_main_context_acquire (context);
910 g_return_if_fail (acquired_context);
912 if (context == g_main_context_default ())
915 g_main_context_ref (context);
917 stack = g_private_get (&thread_context_stack);
920 stack = g_queue_new ();
921 g_private_set (&thread_context_stack, stack);
924 g_queue_push_head (stack, context);
926 TRACE (GLIB_MAIN_CONTEXT_PUSH_THREAD_DEFAULT (context));
930 * g_main_context_pop_thread_default:
931 * @context: (nullable): a #GMainContext, or %NULL for the global-default
934 * Pops @context off the thread-default context stack (verifying that
935 * it was on the top of the stack).
940 g_main_context_pop_thread_default (GMainContext *context)
944 if (context == g_main_context_default ())
947 stack = g_private_get (&thread_context_stack);
949 g_return_if_fail (stack != NULL);
950 g_return_if_fail (g_queue_peek_head (stack) == context);
952 TRACE (GLIB_MAIN_CONTEXT_POP_THREAD_DEFAULT (context));
954 g_queue_pop_head (stack);
956 g_main_context_release (context);
958 g_main_context_unref (context);
962 * g_main_context_get_thread_default:
964 * Gets the thread-default #GMainContext for this thread. Asynchronous
965 * operations that want to be able to be run in contexts other than
966 * the default one should call this method or
967 * g_main_context_ref_thread_default() to get a #GMainContext to add
968 * their #GSources to. (Note that even in single-threaded
969 * programs applications may sometimes want to temporarily push a
970 * non-default context, so it is not safe to assume that this will
971 * always return %NULL if you are running in the default thread.)
973 * If you need to hold a reference on the context, use
974 * g_main_context_ref_thread_default() instead.
976 * Returns: (transfer none) (nullable): the thread-default #GMainContext, or
977 * %NULL if the thread-default context is the global-default main context.
982 g_main_context_get_thread_default (void)
986 stack = g_private_get (&thread_context_stack);
988 return g_queue_peek_head (stack);
994 * g_main_context_ref_thread_default:
996 * Gets the thread-default #GMainContext for this thread, as with
997 * g_main_context_get_thread_default(), but also adds a reference to
998 * it with g_main_context_ref(). In addition, unlike
999 * g_main_context_get_thread_default(), if the thread-default context
1000 * is the global-default context, this will return that #GMainContext
1001 * (with a ref added to it) rather than returning %NULL.
1003 * Returns: (transfer full): the thread-default #GMainContext. Unref
1004 * with g_main_context_unref() when you are done with it.
1009 g_main_context_ref_thread_default (void)
1011 GMainContext *context;
1013 context = g_main_context_get_thread_default ();
1015 context = g_main_context_default ();
1016 return g_main_context_ref (context);
1019 /* Hooks for adding to the main loop */
1023 * @source_funcs: structure containing functions that implement
1024 * the sources behavior.
1025 * @struct_size: size of the #GSource structure to create.
1027 * Creates a new #GSource structure. The size is specified to
1028 * allow creating structures derived from #GSource that contain
1029 * additional data. The size passed in must be at least
1030 * `sizeof (GSource)`.
1032 * The source will not initially be associated with any #GMainContext
1033 * and must be added to one with g_source_attach() before it will be
1036 * Returns: the newly-created #GSource.
1039 g_source_new (GSourceFuncs *source_funcs,
1044 g_return_val_if_fail (source_funcs != NULL, NULL);
1045 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
1047 source = (GSource*) g_malloc0 (struct_size);
1048 source->priv = g_slice_new0 (GSourcePrivate);
1049 source->source_funcs = source_funcs;
1050 source->ref_count = 1;
1052 source->priority = G_PRIORITY_DEFAULT;
1054 source->flags = G_HOOK_FLAG_ACTIVE;
1056 source->priv->ready_time = -1;
1058 /* NULL/0 initialization for all other fields */
1060 TRACE (GLIB_SOURCE_NEW (source, source_funcs->prepare, source_funcs->check,
1061 source_funcs->dispatch, source_funcs->finalize,
1068 * g_source_set_dispose_function:
1069 * @source: A #GSource to set the dispose function on
1070 * @dispose: #GSourceDisposeFunc to set on the source
1072 * Set @dispose as dispose function on @source. @dispose will be called once
1073 * the reference count of @source reaches 0 but before any of the state of the
1074 * source is freed, especially before the finalize function is called.
1076 * This means that at this point @source is still a valid #GSource and it is
1077 * allow for the reference count to increase again until @dispose returns.
1079 * The dispose function can be used to clear any "weak" references to the
1080 * @source in other data structures in a thread-safe way where it is possible
1081 * for another thread to increase the reference count of @source again while
1082 * it is being freed.
1084 * The finalize function can not be used for this purpose as at that point
1085 * @source is already partially freed and not valid anymore.
1087 * This should only ever be called from #GSource implementations.
1092 g_source_set_dispose_function (GSource *source,
1093 GSourceDisposeFunc dispose)
1095 g_return_if_fail (source != NULL);
1096 g_return_if_fail (source->priv->dispose == NULL);
1097 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1098 source->priv->dispose = dispose;
1101 /* Holds context's lock */
1103 g_source_iter_init (GSourceIter *iter,
1104 GMainContext *context,
1105 gboolean may_modify)
1107 iter->context = context;
1108 iter->current_list = NULL;
1109 iter->source = NULL;
1110 iter->may_modify = may_modify;
1113 /* Holds context's lock */
1115 g_source_iter_next (GSourceIter *iter, GSource **source)
1117 GSource *next_source;
1120 next_source = iter->source->next;
1126 if (iter->current_list)
1127 iter->current_list = iter->current_list->next;
1129 iter->current_list = iter->context->source_lists;
1131 if (iter->current_list)
1133 GSourceList *source_list = iter->current_list->data;
1135 next_source = source_list->head;
1139 /* Note: unreffing iter->source could potentially cause its
1140 * GSourceList to be removed from source_lists (if iter->source is
1141 * the only source in its list, and it is destroyed), so we have to
1142 * keep it reffed until after we advance iter->current_list, above.
1144 * Also we first have to ref the next source before unreffing the
1145 * previous one as unreffing the previous source can potentially
1146 * free the next one.
1148 if (next_source && iter->may_modify)
1149 g_source_ref (next_source);
1151 if (iter->source && iter->may_modify)
1152 g_source_unref_internal (iter->source, iter->context, TRUE);
1153 iter->source = next_source;
1155 *source = iter->source;
1156 return *source != NULL;
1159 /* Holds context's lock. Only necessary to call if you broke out of
1160 * the g_source_iter_next() loop early.
1163 g_source_iter_clear (GSourceIter *iter)
1165 if (iter->source && iter->may_modify)
1167 g_source_unref_internal (iter->source, iter->context, TRUE);
1168 iter->source = NULL;
1172 /* Holds context's lock
1174 static GSourceList *
1175 find_source_list_for_priority (GMainContext *context,
1180 GSourceList *source_list;
1183 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
1185 source_list = iter->data;
1187 if (source_list->priority == priority)
1190 if (source_list->priority > priority)
1195 source_list = g_slice_new0 (GSourceList);
1196 source_list->priority = priority;
1197 context->source_lists = g_list_insert_before (context->source_lists,
1207 source_list = g_slice_new0 (GSourceList);
1208 source_list->priority = priority;
1211 context->source_lists = g_list_append (NULL, source_list);
1214 /* This just appends source_list to the end of
1215 * context->source_lists without having to walk the list again.
1217 last = g_list_append (last, source_list);
1223 /* Holds context's lock
1226 source_add_to_context (GSource *source,
1227 GMainContext *context)
1229 GSourceList *source_list;
1230 GSource *prev, *next;
1232 source_list = find_source_list_for_priority (context, source->priority, TRUE);
1234 if (source->priv->parent_source)
1236 g_assert (source_list->head != NULL);
1238 /* Put the source immediately before its parent */
1239 prev = source->priv->parent_source->prev;
1240 next = source->priv->parent_source;
1244 prev = source_list->tail;
1248 source->next = next;
1250 next->prev = source;
1252 source_list->tail = source;
1254 source->prev = prev;
1256 prev->next = source;
1258 source_list->head = source;
1261 /* Holds context's lock
1264 source_remove_from_context (GSource *source,
1265 GMainContext *context)
1267 GSourceList *source_list;
1269 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1270 g_return_if_fail (source_list != NULL);
1273 source->prev->next = source->next;
1275 source_list->head = source->next;
1278 source->next->prev = source->prev;
1280 source_list->tail = source->prev;
1282 source->prev = NULL;
1283 source->next = NULL;
1285 if (source_list->head == NULL)
1287 context->source_lists = g_list_remove (context->source_lists, source_list);
1288 g_slice_free (GSourceList, source_list);
1293 g_source_attach_unlocked (GSource *source,
1294 GMainContext *context,
1300 /* The counter may have wrapped, so we must ensure that we do not
1301 * reuse the source id of an existing source.
1304 id = context->next_id++;
1305 while (id == 0 || g_hash_table_contains (context->sources, GUINT_TO_POINTER (id)));
1307 source->context = context;
1308 source->source_id = id;
1309 g_source_ref (source);
1311 g_hash_table_insert (context->sources, GUINT_TO_POINTER (id), source);
1313 source_add_to_context (source, context);
1315 if (!SOURCE_BLOCKED (source))
1317 tmp_list = source->poll_fds;
1320 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1321 tmp_list = tmp_list->next;
1324 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1325 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1328 tmp_list = source->priv->child_sources;
1331 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1332 tmp_list = tmp_list->next;
1335 /* If another thread has acquired the context, wake it up since it
1336 * might be in poll() right now.
1339 (context->flags & G_MAIN_CONTEXT_FLAGS_OWNERLESS_POLLING ||
1340 (context->owner && context->owner != G_THREAD_SELF)))
1342 g_wakeup_signal (context->wakeup);
1345 g_trace_mark (G_TRACE_CURRENT_TIME, 0,
1346 "GLib", "g_source_attach",
1348 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
1351 return source->source_id;
1356 * @source: a #GSource
1357 * @context: (nullable): a #GMainContext (if %NULL, the global-default
1358 * main context will be used)
1360 * Adds a #GSource to a @context so that it will be executed within
1361 * that context. Remove it by calling g_source_destroy().
1363 * This function is safe to call from any thread, regardless of which thread
1364 * the @context is running in.
1366 * Returns: the ID (greater than 0) for the source within the
1370 g_source_attach (GSource *source,
1371 GMainContext *context)
1375 g_return_val_if_fail (source != NULL, 0);
1376 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1377 g_return_val_if_fail (source->context == NULL, 0);
1378 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1381 context = g_main_context_default ();
1383 LOCK_CONTEXT (context);
1385 result = g_source_attach_unlocked (source, context, TRUE);
1387 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source), source, context,
1390 UNLOCK_CONTEXT (context);
1396 g_source_destroy_internal (GSource *source,
1397 GMainContext *context,
1400 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source), source,
1404 LOCK_CONTEXT (context);
1406 if (!SOURCE_DESTROYED (source))
1409 gpointer old_cb_data;
1410 GSourceCallbackFuncs *old_cb_funcs;
1412 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1414 old_cb_data = source->callback_data;
1415 old_cb_funcs = source->callback_funcs;
1417 source->callback_data = NULL;
1418 source->callback_funcs = NULL;
1422 UNLOCK_CONTEXT (context);
1423 old_cb_funcs->unref (old_cb_data);
1424 LOCK_CONTEXT (context);
1427 if (!SOURCE_BLOCKED (source))
1429 tmp_list = source->poll_fds;
1432 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1433 tmp_list = tmp_list->next;
1436 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1437 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1440 while (source->priv->child_sources)
1441 g_child_source_remove_internal (source->priv->child_sources->data, context);
1443 if (source->priv->parent_source)
1444 g_child_source_remove_internal (source, context);
1446 g_source_unref_internal (source, context, TRUE);
1450 UNLOCK_CONTEXT (context);
1455 * @source: a #GSource
1457 * Removes a source from its #GMainContext, if any, and mark it as
1458 * destroyed. The source cannot be subsequently added to another
1459 * context. It is safe to call this on sources which have already been
1460 * removed from their context.
1462 * This does not unref the #GSource: if you still hold a reference, use
1463 * g_source_unref() to drop it.
1465 * This function is safe to call from any thread, regardless of which thread
1466 * the #GMainContext is running in.
1468 * If the source is currently attached to a #GMainContext, destroying it
1469 * will effectively unset the callback similar to calling g_source_set_callback().
1470 * This can mean, that the data's #GDestroyNotify gets called right away.
1473 g_source_destroy (GSource *source)
1475 GMainContext *context;
1477 g_return_if_fail (source != NULL);
1478 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1480 context = source->context;
1483 g_source_destroy_internal (source, context, FALSE);
1485 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1490 * @source: a #GSource
1492 * Returns the numeric ID for a particular source. The ID of a source
1493 * is a positive integer which is unique within a particular main loop
1494 * context. The reverse
1495 * mapping from ID to source is done by g_main_context_find_source_by_id().
1497 * You can only call this function while the source is associated to a
1498 * #GMainContext instance; calling this function before g_source_attach()
1499 * or after g_source_destroy() yields undefined behavior. The ID returned
1500 * is unique within the #GMainContext instance passed to g_source_attach().
1502 * Returns: the ID (greater than 0) for the source
1505 g_source_get_id (GSource *source)
1509 g_return_val_if_fail (source != NULL, 0);
1510 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
1511 g_return_val_if_fail (source->context != NULL, 0);
1513 LOCK_CONTEXT (source->context);
1514 result = source->source_id;
1515 UNLOCK_CONTEXT (source->context);
1521 * g_source_get_context:
1522 * @source: a #GSource
1524 * Gets the #GMainContext with which the source is associated.
1526 * You can call this on a source that has been destroyed, provided
1527 * that the #GMainContext it was attached to still exists (in which
1528 * case it will return that #GMainContext). In particular, you can
1529 * always call this function on the source returned from
1530 * g_main_current_source(). But calling this function on a source
1531 * whose #GMainContext has been destroyed is an error.
1533 * Returns: (transfer none) (nullable): the #GMainContext with which the
1534 * source is associated, or %NULL if the context has not
1535 * yet been added to a source.
1538 g_source_get_context (GSource *source)
1540 g_return_val_if_fail (source != NULL, NULL);
1541 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
1542 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1544 return source->context;
1548 * g_source_add_poll:
1549 * @source:a #GSource
1550 * @fd: a #GPollFD structure holding information about a file
1551 * descriptor to watch.
1553 * Adds a file descriptor to the set of file descriptors polled for
1554 * this source. This is usually combined with g_source_new() to add an
1555 * event source. The event source's check function will typically test
1556 * the @revents field in the #GPollFD struct and return %TRUE if events need
1559 * This API is only intended to be used by implementations of #GSource.
1560 * Do not call this API on a #GSource that you did not create.
1562 * Using this API forces the linear scanning of event sources on each
1563 * main loop iteration. Newly-written event sources should try to use
1564 * g_source_add_unix_fd() instead of this API.
1567 g_source_add_poll (GSource *source,
1570 GMainContext *context;
1572 g_return_if_fail (source != NULL);
1573 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1574 g_return_if_fail (fd != NULL);
1575 g_return_if_fail (!SOURCE_DESTROYED (source));
1577 context = source->context;
1580 LOCK_CONTEXT (context);
1582 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1586 if (!SOURCE_BLOCKED (source))
1587 g_main_context_add_poll_unlocked (context, source->priority, fd);
1588 UNLOCK_CONTEXT (context);
1593 * g_source_remove_poll:
1594 * @source:a #GSource
1595 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1597 * Removes a file descriptor from the set of file descriptors polled for
1600 * This API is only intended to be used by implementations of #GSource.
1601 * Do not call this API on a #GSource that you did not create.
1604 g_source_remove_poll (GSource *source,
1607 GMainContext *context;
1609 g_return_if_fail (source != NULL);
1610 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1611 g_return_if_fail (fd != NULL);
1612 g_return_if_fail (!SOURCE_DESTROYED (source));
1614 context = source->context;
1617 LOCK_CONTEXT (context);
1619 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1623 if (!SOURCE_BLOCKED (source))
1624 g_main_context_remove_poll_unlocked (context, fd);
1625 UNLOCK_CONTEXT (context);
1630 * g_source_add_child_source:
1631 * @source:a #GSource
1632 * @child_source: a second #GSource that @source should "poll"
1634 * Adds @child_source to @source as a "polled" source; when @source is
1635 * added to a #GMainContext, @child_source will be automatically added
1636 * with the same priority, when @child_source is triggered, it will
1637 * cause @source to dispatch (in addition to calling its own
1638 * callback), and when @source is destroyed, it will destroy
1639 * @child_source as well. (@source will also still be dispatched if
1640 * its own prepare/check functions indicate that it is ready.)
1642 * If you don't need @child_source to do anything on its own when it
1643 * triggers, you can call g_source_set_dummy_callback() on it to set a
1644 * callback that does nothing (except return %TRUE if appropriate).
1646 * @source will hold a reference on @child_source while @child_source
1647 * is attached to it.
1649 * This API is only intended to be used by implementations of #GSource.
1650 * Do not call this API on a #GSource that you did not create.
1655 g_source_add_child_source (GSource *source,
1656 GSource *child_source)
1658 GMainContext *context;
1660 g_return_if_fail (source != NULL);
1661 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1662 g_return_if_fail (child_source != NULL);
1663 g_return_if_fail (g_atomic_int_get (&child_source->ref_count) > 0);
1664 g_return_if_fail (!SOURCE_DESTROYED (source));
1665 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1666 g_return_if_fail (child_source->context == NULL);
1667 g_return_if_fail (child_source->priv->parent_source == NULL);
1669 context = source->context;
1672 LOCK_CONTEXT (context);
1674 TRACE (GLIB_SOURCE_ADD_CHILD_SOURCE (source, child_source));
1676 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1677 g_source_ref (child_source));
1678 child_source->priv->parent_source = source;
1679 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1680 if (SOURCE_BLOCKED (source))
1681 block_source (child_source);
1685 g_source_attach_unlocked (child_source, context, TRUE);
1686 UNLOCK_CONTEXT (context);
1691 g_child_source_remove_internal (GSource *child_source,
1692 GMainContext *context)
1694 GSource *parent_source = child_source->priv->parent_source;
1696 parent_source->priv->child_sources =
1697 g_slist_remove (parent_source->priv->child_sources, child_source);
1698 child_source->priv->parent_source = NULL;
1700 g_source_destroy_internal (child_source, context, TRUE);
1701 g_source_unref_internal (child_source, context, TRUE);
1705 * g_source_remove_child_source:
1706 * @source:a #GSource
1707 * @child_source: a #GSource previously passed to
1708 * g_source_add_child_source().
1710 * Detaches @child_source from @source and destroys it.
1712 * This API is only intended to be used by implementations of #GSource.
1713 * Do not call this API on a #GSource that you did not create.
1718 g_source_remove_child_source (GSource *source,
1719 GSource *child_source)
1721 GMainContext *context;
1723 g_return_if_fail (source != NULL);
1724 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1725 g_return_if_fail (child_source != NULL);
1726 g_return_if_fail (g_atomic_int_get (&child_source->ref_count) > 0);
1727 g_return_if_fail (child_source->priv->parent_source == source);
1728 g_return_if_fail (!SOURCE_DESTROYED (source));
1729 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1731 context = source->context;
1734 LOCK_CONTEXT (context);
1736 g_child_source_remove_internal (child_source, context);
1739 UNLOCK_CONTEXT (context);
1743 g_source_callback_ref (gpointer cb_data)
1745 GSourceCallback *callback = cb_data;
1747 g_atomic_int_inc (&callback->ref_count);
1751 g_source_callback_unref (gpointer cb_data)
1753 GSourceCallback *callback = cb_data;
1755 if (g_atomic_int_dec_and_test (&callback->ref_count))
1757 if (callback->notify)
1758 callback->notify (callback->data);
1764 g_source_callback_get (gpointer cb_data,
1769 GSourceCallback *callback = cb_data;
1771 *func = callback->func;
1772 *data = callback->data;
1775 static GSourceCallbackFuncs g_source_callback_funcs = {
1776 g_source_callback_ref,
1777 g_source_callback_unref,
1778 g_source_callback_get,
1782 * g_source_set_callback_indirect:
1783 * @source: the source
1784 * @callback_data: pointer to callback data "object"
1785 * @callback_funcs: functions for reference counting @callback_data
1786 * and getting the callback and data
1788 * Sets the callback function storing the data as a refcounted callback
1789 * "object". This is used internally. Note that calling
1790 * g_source_set_callback_indirect() assumes
1791 * an initial reference count on @callback_data, and thus
1792 * @callback_funcs->unref will eventually be called once more
1793 * than @callback_funcs->ref.
1795 * It is safe to call this function multiple times on a source which has already
1796 * been attached to a context. The changes will take effect for the next time
1797 * the source is dispatched after this call returns.
1800 g_source_set_callback_indirect (GSource *source,
1801 gpointer callback_data,
1802 GSourceCallbackFuncs *callback_funcs)
1804 GMainContext *context;
1805 gpointer old_cb_data;
1806 GSourceCallbackFuncs *old_cb_funcs;
1808 g_return_if_fail (source != NULL);
1809 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1810 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1812 context = source->context;
1815 LOCK_CONTEXT (context);
1817 if (callback_funcs != &g_source_callback_funcs)
1819 TRACE (GLIB_SOURCE_SET_CALLBACK_INDIRECT (source, callback_data,
1820 callback_funcs->ref,
1821 callback_funcs->unref,
1822 callback_funcs->get));
1825 old_cb_data = source->callback_data;
1826 old_cb_funcs = source->callback_funcs;
1828 source->callback_data = callback_data;
1829 source->callback_funcs = callback_funcs;
1832 UNLOCK_CONTEXT (context);
1835 old_cb_funcs->unref (old_cb_data);
1839 * g_source_set_callback:
1840 * @source: the source
1841 * @func: a callback function
1842 * @data: the data to pass to callback function
1843 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
1845 * Sets the callback function for a source. The callback for a source is
1846 * called from the source's dispatch function.
1848 * The exact type of @func depends on the type of source; ie. you
1849 * should not count on @func being called with @data as its first
1850 * parameter. Cast @func with G_SOURCE_FUNC() to avoid warnings about
1851 * incompatible function types.
1853 * See [memory management of sources][mainloop-memory-management] for details
1854 * on how to handle memory management of @data.
1856 * Typically, you won't use this function. Instead use functions specific
1857 * to the type of source you are using, such as g_idle_add() or g_timeout_add().
1859 * It is safe to call this function multiple times on a source which has already
1860 * been attached to a context. The changes will take effect for the next time
1861 * the source is dispatched after this call returns.
1863 * Note that g_source_destroy() for a currently attached source has the effect
1864 * of also unsetting the callback.
1867 g_source_set_callback (GSource *source,
1870 GDestroyNotify notify)
1872 GSourceCallback *new_callback;
1874 g_return_if_fail (source != NULL);
1875 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1877 TRACE (GLIB_SOURCE_SET_CALLBACK (source, func, data, notify));
1879 new_callback = g_new (GSourceCallback, 1);
1881 new_callback->ref_count = 1;
1882 new_callback->func = func;
1883 new_callback->data = data;
1884 new_callback->notify = notify;
1886 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1891 * g_source_set_funcs:
1892 * @source: a #GSource
1893 * @funcs: the new #GSourceFuncs
1895 * Sets the source functions (can be used to override
1896 * default implementations) of an unattached source.
1901 g_source_set_funcs (GSource *source,
1902 GSourceFuncs *funcs)
1904 g_return_if_fail (source != NULL);
1905 g_return_if_fail (source->context == NULL);
1906 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1907 g_return_if_fail (funcs != NULL);
1909 source->source_funcs = funcs;
1913 g_source_set_priority_unlocked (GSource *source,
1914 GMainContext *context,
1919 g_return_if_fail (source->priv->parent_source == NULL ||
1920 source->priv->parent_source->priority == priority);
1922 TRACE (GLIB_SOURCE_SET_PRIORITY (source, context, priority));
1926 /* Remove the source from the context's source and then
1927 * add it back after so it is sorted in the correct place
1929 source_remove_from_context (source, source->context);
1932 source->priority = priority;
1936 source_add_to_context (source, source->context);
1938 if (!SOURCE_BLOCKED (source))
1940 tmp_list = source->poll_fds;
1943 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1944 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1946 tmp_list = tmp_list->next;
1949 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1951 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1952 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1957 if (source->priv->child_sources)
1959 tmp_list = source->priv->child_sources;
1962 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1963 tmp_list = tmp_list->next;
1969 * g_source_set_priority:
1970 * @source: a #GSource
1971 * @priority: the new priority.
1973 * Sets the priority of a source. While the main loop is being run, a
1974 * source will be dispatched if it is ready to be dispatched and no
1975 * sources at a higher (numerically smaller) priority are ready to be
1978 * A child source always has the same priority as its parent. It is not
1979 * permitted to change the priority of a source once it has been added
1980 * as a child of another source.
1983 g_source_set_priority (GSource *source,
1986 GMainContext *context;
1988 g_return_if_fail (source != NULL);
1989 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
1990 g_return_if_fail (source->priv->parent_source == NULL);
1992 context = source->context;
1995 LOCK_CONTEXT (context);
1996 g_source_set_priority_unlocked (source, context, priority);
1998 UNLOCK_CONTEXT (context);
2002 * g_source_get_priority:
2003 * @source: a #GSource
2005 * Gets the priority of a source.
2007 * Returns: the priority of the source
2010 g_source_get_priority (GSource *source)
2012 g_return_val_if_fail (source != NULL, 0);
2013 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
2015 return source->priority;
2019 * g_source_set_ready_time:
2020 * @source: a #GSource
2021 * @ready_time: the monotonic time at which the source will be ready,
2022 * 0 for "immediately", -1 for "never"
2024 * Sets a #GSource to be dispatched when the given monotonic time is
2025 * reached (or passed). If the monotonic time is in the past (as it
2026 * always will be if @ready_time is 0) then the source will be
2027 * dispatched immediately.
2029 * If @ready_time is -1 then the source is never woken up on the basis
2030 * of the passage of time.
2032 * Dispatching the source does not reset the ready time. You should do
2033 * so yourself, from the source dispatch function.
2035 * Note that if you have a pair of sources where the ready time of one
2036 * suggests that it will be delivered first but the priority for the
2037 * other suggests that it would be delivered first, and the ready time
2038 * for both sources is reached during the same main context iteration,
2039 * then the order of dispatch is undefined.
2041 * It is a no-op to call this function on a #GSource which has already been
2042 * destroyed with g_source_destroy().
2044 * This API is only intended to be used by implementations of #GSource.
2045 * Do not call this API on a #GSource that you did not create.
2050 g_source_set_ready_time (GSource *source,
2053 GMainContext *context;
2055 g_return_if_fail (source != NULL);
2056 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2058 context = source->context;
2061 LOCK_CONTEXT (context);
2063 if (source->priv->ready_time == ready_time)
2066 UNLOCK_CONTEXT (context);
2071 source->priv->ready_time = ready_time;
2073 TRACE (GLIB_SOURCE_SET_READY_TIME (source, ready_time));
2077 /* Quite likely that we need to change the timeout on the poll */
2078 if (!SOURCE_BLOCKED (source))
2079 g_wakeup_signal (context->wakeup);
2080 UNLOCK_CONTEXT (context);
2085 * g_source_get_ready_time:
2086 * @source: a #GSource
2088 * Gets the "ready time" of @source, as set by
2089 * g_source_set_ready_time().
2091 * Any time before the current monotonic time (including 0) is an
2092 * indication that the source will fire immediately.
2094 * Returns: the monotonic ready time, -1 for "never"
2097 g_source_get_ready_time (GSource *source)
2099 g_return_val_if_fail (source != NULL, -1);
2100 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, -1);
2102 return source->priv->ready_time;
2106 * g_source_set_can_recurse:
2107 * @source: a #GSource
2108 * @can_recurse: whether recursion is allowed for this source
2110 * Sets whether a source can be called recursively. If @can_recurse is
2111 * %TRUE, then while the source is being dispatched then this source
2112 * will be processed normally. Otherwise, all processing of this
2113 * source is blocked until the dispatch function returns.
2116 g_source_set_can_recurse (GSource *source,
2117 gboolean can_recurse)
2119 GMainContext *context;
2121 g_return_if_fail (source != NULL);
2122 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2124 context = source->context;
2127 LOCK_CONTEXT (context);
2130 source->flags |= G_SOURCE_CAN_RECURSE;
2132 source->flags &= ~G_SOURCE_CAN_RECURSE;
2135 UNLOCK_CONTEXT (context);
2139 * g_source_get_can_recurse:
2140 * @source: a #GSource
2142 * Checks whether a source is allowed to be called recursively.
2143 * see g_source_set_can_recurse().
2145 * Returns: whether recursion is allowed.
2148 g_source_get_can_recurse (GSource *source)
2150 g_return_val_if_fail (source != NULL, FALSE);
2151 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, FALSE);
2153 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
2157 g_source_set_name_full (GSource *source,
2161 GMainContext *context;
2163 g_return_if_fail (source != NULL);
2164 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2166 context = source->context;
2169 LOCK_CONTEXT (context);
2171 TRACE (GLIB_SOURCE_SET_NAME (source, name));
2173 /* setting back to NULL is allowed, just because it's
2174 * weird if get_name can return NULL but you can't
2178 if (!source->priv->static_name)
2179 g_free (source->name);
2182 source->name = (char *)name;
2184 source->name = g_strdup (name);
2186 source->priv->static_name = is_static;
2189 UNLOCK_CONTEXT (context);
2193 * g_source_set_name:
2194 * @source: a #GSource
2195 * @name: debug name for the source
2197 * Sets a name for the source, used in debugging and profiling.
2198 * The name defaults to #NULL.
2200 * The source name should describe in a human-readable way
2201 * what the source does. For example, "X11 event queue"
2202 * or "GTK repaint idle handler" or whatever it is.
2204 * It is permitted to call this function multiple times, but is not
2205 * recommended due to the potential performance impact. For example,
2206 * one could change the name in the "check" function of a #GSourceFuncs
2207 * to include details like the event type in the source name.
2209 * Use caution if changing the name while another thread may be
2210 * accessing it with g_source_get_name(); that function does not copy
2211 * the value, and changing the value will free it while the other thread
2212 * may be attempting to use it.
2214 * Also see g_source_set_static_name().
2219 g_source_set_name (GSource *source,
2222 g_source_set_name_full (source, name, FALSE);
2226 * g_source_set_static_name:
2227 * @source: a #GSource
2228 * @name: debug name for the source
2230 * A variant of g_source_set_name() that does not
2231 * duplicate the @name, and can only be used with
2237 g_source_set_static_name (GSource *source,
2240 g_source_set_name_full (source, name, TRUE);
2244 * g_source_get_name:
2245 * @source: a #GSource
2247 * Gets a name for the source, used in debugging and profiling. The
2248 * name may be #NULL if it has never been set with g_source_set_name().
2250 * Returns: (nullable): the name of the source
2255 g_source_get_name (GSource *source)
2257 g_return_val_if_fail (source != NULL, NULL);
2258 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
2260 return source->name;
2264 * g_source_set_name_by_id:
2265 * @tag: a #GSource ID
2266 * @name: debug name for the source
2268 * Sets the name of a source using its ID.
2270 * This is a convenience utility to set source names from the return
2271 * value of g_idle_add(), g_timeout_add(), etc.
2273 * It is a programmer error to attempt to set the name of a non-existent
2276 * More specifically: source IDs can be reissued after a source has been
2277 * destroyed and therefore it is never valid to use this function with a
2278 * source ID which may have already been removed. An example is when
2279 * scheduling an idle to run in another thread with g_idle_add(): the
2280 * idle may already have run and been removed by the time this function
2281 * is called on its (now invalid) source ID. This source ID may have
2282 * been reissued, leading to the operation being performed against the
2288 g_source_set_name_by_id (guint tag,
2293 g_return_if_fail (tag > 0);
2295 source = g_main_context_find_source_by_id (NULL, tag);
2299 g_source_set_name (source, name);
2305 * @source: a #GSource
2307 * Increases the reference count on a source by one.
2312 g_source_ref (GSource *source)
2314 g_return_val_if_fail (source != NULL, NULL);
2315 /* We allow ref_count == 0 here to allow the dispose function to resurrect
2316 * the GSource if needed */
2317 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) >= 0, NULL);
2319 g_atomic_int_inc (&source->ref_count);
2324 /* g_source_unref() but possible to call within context lock
2327 g_source_unref_internal (GSource *source,
2328 GMainContext *context,
2331 gpointer old_cb_data = NULL;
2332 GSourceCallbackFuncs *old_cb_funcs = NULL;
2334 g_return_if_fail (source != NULL);
2336 if (!have_lock && context)
2337 LOCK_CONTEXT (context);
2339 if (g_atomic_int_dec_and_test (&source->ref_count))
2341 /* If there's a dispose function, call this first */
2342 if (source->priv->dispose)
2344 /* Temporarily increase the ref count again so that GSource methods
2345 * can be called from dispose(). */
2346 g_atomic_int_inc (&source->ref_count);
2348 UNLOCK_CONTEXT (context);
2349 source->priv->dispose (source);
2351 LOCK_CONTEXT (context);
2353 /* Now the reference count might be bigger than 0 again, in which
2354 * case we simply return from here before freeing the source */
2355 if (!g_atomic_int_dec_and_test (&source->ref_count))
2357 if (!have_lock && context)
2358 UNLOCK_CONTEXT (context);
2363 TRACE (GLIB_SOURCE_BEFORE_FREE (source, context,
2364 source->source_funcs->finalize));
2366 old_cb_data = source->callback_data;
2367 old_cb_funcs = source->callback_funcs;
2369 source->callback_data = NULL;
2370 source->callback_funcs = NULL;
2374 if (!SOURCE_DESTROYED (source))
2375 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
2376 source_remove_from_context (source, context);
2378 g_hash_table_remove (context->sources, GUINT_TO_POINTER (source->source_id));
2381 if (source->source_funcs->finalize)
2385 /* Temporarily increase the ref count again so that GSource methods
2386 * can be called from finalize(). */
2387 g_atomic_int_inc (&source->ref_count);
2389 UNLOCK_CONTEXT (context);
2390 source->source_funcs->finalize (source);
2392 LOCK_CONTEXT (context);
2393 old_ref_count = g_atomic_int_add (&source->ref_count, -1);
2394 g_warn_if_fail (old_ref_count == 1);
2401 /* Temporarily increase the ref count again so that GSource methods
2402 * can be called from callback_funcs.unref(). */
2403 g_atomic_int_inc (&source->ref_count);
2405 UNLOCK_CONTEXT (context);
2407 old_cb_funcs->unref (old_cb_data);
2410 LOCK_CONTEXT (context);
2411 old_ref_count = g_atomic_int_add (&source->ref_count, -1);
2412 g_warn_if_fail (old_ref_count == 1);
2415 if (!source->priv->static_name)
2416 g_free (source->name);
2417 source->name = NULL;
2419 g_slist_free (source->poll_fds);
2420 source->poll_fds = NULL;
2422 g_slist_free_full (source->priv->fds, g_free);
2424 while (source->priv->child_sources)
2426 GSource *child_source = source->priv->child_sources->data;
2428 source->priv->child_sources =
2429 g_slist_remove (source->priv->child_sources, child_source);
2430 child_source->priv->parent_source = NULL;
2432 g_source_unref_internal (child_source, context, TRUE);
2435 g_slice_free (GSourcePrivate, source->priv);
2436 source->priv = NULL;
2441 if (!have_lock && context)
2442 UNLOCK_CONTEXT (context);
2447 * @source: a #GSource
2449 * Decreases the reference count of a source by one. If the
2450 * resulting reference count is zero the source and associated
2451 * memory will be destroyed.
2454 g_source_unref (GSource *source)
2456 g_return_if_fail (source != NULL);
2457 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2459 g_source_unref_internal (source, source->context, FALSE);
2463 * g_main_context_find_source_by_id:
2464 * @context: (nullable): a #GMainContext (if %NULL, the global-default
2465 * main context will be used)
2466 * @source_id: the source ID, as returned by g_source_get_id().
2468 * Finds a #GSource given a pair of context and ID.
2470 * It is a programmer error to attempt to look up a non-existent source.
2472 * More specifically: source IDs can be reissued after a source has been
2473 * destroyed and therefore it is never valid to use this function with a
2474 * source ID which may have already been removed. An example is when
2475 * scheduling an idle to run in another thread with g_idle_add(): the
2476 * idle may already have run and been removed by the time this function
2477 * is called on its (now invalid) source ID. This source ID may have
2478 * been reissued, leading to the operation being performed against the
2481 * Returns: (transfer none): the #GSource
2484 g_main_context_find_source_by_id (GMainContext *context,
2489 g_return_val_if_fail (source_id > 0, NULL);
2491 if (context == NULL)
2492 context = g_main_context_default ();
2494 LOCK_CONTEXT (context);
2495 source = g_hash_table_lookup (context->sources, GUINT_TO_POINTER (source_id));
2496 UNLOCK_CONTEXT (context);
2498 if (source && SOURCE_DESTROYED (source))
2505 * g_main_context_find_source_by_funcs_user_data:
2506 * @context: (nullable): a #GMainContext (if %NULL, the global-default
2507 * main context will be used).
2508 * @funcs: the @source_funcs passed to g_source_new().
2509 * @user_data: the user data from the callback.
2511 * Finds a source with the given source functions and user data. If
2512 * multiple sources exist with the same source function and user data,
2513 * the first one found will be returned.
2515 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2518 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2519 GSourceFuncs *funcs,
2525 g_return_val_if_fail (funcs != NULL, NULL);
2527 if (context == NULL)
2528 context = g_main_context_default ();
2530 LOCK_CONTEXT (context);
2532 g_source_iter_init (&iter, context, FALSE);
2533 while (g_source_iter_next (&iter, &source))
2535 if (!SOURCE_DESTROYED (source) &&
2536 source->source_funcs == funcs &&
2537 source->callback_funcs)
2539 GSourceFunc callback;
2540 gpointer callback_data;
2542 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2544 if (callback_data == user_data)
2548 g_source_iter_clear (&iter);
2550 UNLOCK_CONTEXT (context);
2556 * g_main_context_find_source_by_user_data:
2557 * @context: (nullable): a #GMainContext (if %NULL, the global-default
2558 * main context will be used)
2559 * @user_data: the user_data for the callback.
2561 * Finds a source with the given user data for the callback. If
2562 * multiple sources exist with the same user data, the first
2563 * one found will be returned.
2565 * Returns: (transfer none): the source, if one was found, otherwise %NULL
2568 g_main_context_find_source_by_user_data (GMainContext *context,
2574 if (context == NULL)
2575 context = g_main_context_default ();
2577 LOCK_CONTEXT (context);
2579 g_source_iter_init (&iter, context, FALSE);
2580 while (g_source_iter_next (&iter, &source))
2582 if (!SOURCE_DESTROYED (source) &&
2583 source->callback_funcs)
2585 GSourceFunc callback;
2586 gpointer callback_data = NULL;
2588 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2590 if (callback_data == user_data)
2594 g_source_iter_clear (&iter);
2596 UNLOCK_CONTEXT (context);
2603 * @tag: the ID of the source to remove.
2605 * Removes the source with the given ID from the default main context. You must
2606 * use g_source_destroy() for sources added to a non-default main context.
2608 * The ID of a #GSource is given by g_source_get_id(), or will be
2609 * returned by the functions g_source_attach(), g_idle_add(),
2610 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2611 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2612 * g_io_add_watch_full().
2614 * It is a programmer error to attempt to remove a non-existent source.
2616 * More specifically: source IDs can be reissued after a source has been
2617 * destroyed and therefore it is never valid to use this function with a
2618 * source ID which may have already been removed. An example is when
2619 * scheduling an idle to run in another thread with g_idle_add(): the
2620 * idle may already have run and been removed by the time this function
2621 * is called on its (now invalid) source ID. This source ID may have
2622 * been reissued, leading to the operation being performed against the
2625 * Returns: %TRUE if the source was found and removed.
2628 g_source_remove (guint tag)
2632 g_return_val_if_fail (tag > 0, FALSE);
2634 source = g_main_context_find_source_by_id (NULL, tag);
2636 g_source_destroy (source);
2638 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2640 return source != NULL;
2644 * g_source_remove_by_user_data:
2645 * @user_data: the user_data for the callback.
2647 * Removes a source from the default main loop context given the user
2648 * data for the callback. If multiple sources exist with the same user
2649 * data, only one will be destroyed.
2651 * Returns: %TRUE if a source was found and removed.
2654 g_source_remove_by_user_data (gpointer user_data)
2658 source = g_main_context_find_source_by_user_data (NULL, user_data);
2661 g_source_destroy (source);
2669 * g_source_remove_by_funcs_user_data:
2670 * @funcs: The @source_funcs passed to g_source_new()
2671 * @user_data: the user data for the callback
2673 * Removes a source from the default main loop context given the
2674 * source functions and user data. If multiple sources exist with the
2675 * same source functions and user data, only one will be destroyed.
2677 * Returns: %TRUE if a source was found and removed.
2680 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2685 g_return_val_if_fail (funcs != NULL, FALSE);
2687 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2690 g_source_destroy (source);
2698 * g_clear_handle_id: (skip)
2699 * @tag_ptr: (not nullable): a pointer to the handler ID
2700 * @clear_func: (not nullable): the function to call to clear the handler
2702 * Clears a numeric handler, such as a #GSource ID.
2704 * @tag_ptr must be a valid pointer to the variable holding the handler.
2706 * If the ID is zero then this function does nothing.
2707 * Otherwise, clear_func() is called with the ID as a parameter, and the tag is
2710 * A macro is also included that allows this function to be used without
2715 #undef g_clear_handle_id
2717 g_clear_handle_id (guint *tag_ptr,
2718 GClearHandleFunc clear_func)
2722 _handle_id = *tag_ptr;
2726 clear_func (_handle_id);
2732 * g_source_add_unix_fd:
2733 * @source: a #GSource
2734 * @fd: the fd to monitor
2735 * @events: an event mask
2737 * Monitors @fd for the IO events in @events.
2739 * The tag returned by this function can be used to remove or modify the
2740 * monitoring of the fd using g_source_remove_unix_fd() or
2741 * g_source_modify_unix_fd().
2743 * It is not necessary to remove the fd before destroying the source; it
2744 * will be cleaned up automatically.
2746 * This API is only intended to be used by implementations of #GSource.
2747 * Do not call this API on a #GSource that you did not create.
2749 * As the name suggests, this function is not available on Windows.
2751 * Returns: (not nullable): an opaque tag
2756 g_source_add_unix_fd (GSource *source,
2758 GIOCondition events)
2760 GMainContext *context;
2763 g_return_val_if_fail (source != NULL, NULL);
2764 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, NULL);
2765 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2767 poll_fd = g_new (GPollFD, 1);
2769 poll_fd->events = events;
2770 poll_fd->revents = 0;
2772 context = source->context;
2775 LOCK_CONTEXT (context);
2777 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2781 if (!SOURCE_BLOCKED (source))
2782 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2783 UNLOCK_CONTEXT (context);
2790 * g_source_modify_unix_fd:
2791 * @source: a #GSource
2792 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2793 * @new_events: the new event mask to watch
2795 * Updates the event mask to watch for the fd identified by @tag.
2797 * @tag is the tag returned from g_source_add_unix_fd().
2799 * If you want to remove a fd, don't set its event mask to zero.
2800 * Instead, call g_source_remove_unix_fd().
2802 * This API is only intended to be used by implementations of #GSource.
2803 * Do not call this API on a #GSource that you did not create.
2805 * As the name suggests, this function is not available on Windows.
2810 g_source_modify_unix_fd (GSource *source,
2812 GIOCondition new_events)
2814 GMainContext *context;
2817 g_return_if_fail (source != NULL);
2818 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2819 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2821 context = source->context;
2824 poll_fd->events = new_events;
2827 g_main_context_wakeup (context);
2831 * g_source_remove_unix_fd:
2832 * @source: a #GSource
2833 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2835 * Reverses the effect of a previous call to g_source_add_unix_fd().
2837 * You only need to call this if you want to remove an fd from being
2838 * watched while keeping the same source around. In the normal case you
2839 * will just want to destroy the source.
2841 * This API is only intended to be used by implementations of #GSource.
2842 * Do not call this API on a #GSource that you did not create.
2844 * As the name suggests, this function is not available on Windows.
2849 g_source_remove_unix_fd (GSource *source,
2852 GMainContext *context;
2855 g_return_if_fail (source != NULL);
2856 g_return_if_fail (g_atomic_int_get (&source->ref_count) > 0);
2857 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2859 context = source->context;
2863 LOCK_CONTEXT (context);
2865 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2869 if (!SOURCE_BLOCKED (source))
2870 g_main_context_remove_poll_unlocked (context, poll_fd);
2872 UNLOCK_CONTEXT (context);
2879 * g_source_query_unix_fd:
2880 * @source: a #GSource
2881 * @tag: (not nullable): the tag from g_source_add_unix_fd()
2883 * Queries the events reported for the fd corresponding to @tag on
2884 * @source during the last poll.
2886 * The return value of this function is only defined when the function
2887 * is called from the check or dispatch functions for @source.
2889 * This API is only intended to be used by implementations of #GSource.
2890 * Do not call this API on a #GSource that you did not create.
2892 * As the name suggests, this function is not available on Windows.
2894 * Returns: the conditions reported on the fd
2899 g_source_query_unix_fd (GSource *source,
2904 g_return_val_if_fail (source != NULL, 0);
2905 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
2906 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2910 return poll_fd->revents;
2912 #endif /* G_OS_UNIX */
2915 * g_get_current_time:
2916 * @result: #GTimeVal structure in which to store current time.
2918 * Equivalent to the UNIX gettimeofday() function, but portable.
2920 * You may find g_get_real_time() to be more convenient.
2922 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use g_get_real_time()
2925 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
2927 g_get_current_time (GTimeVal *result)
2931 g_return_if_fail (result != NULL);
2933 tv = g_get_real_time ();
2935 result->tv_sec = tv / 1000000;
2936 result->tv_usec = tv % 1000000;
2938 G_GNUC_END_IGNORE_DEPRECATIONS
2943 * Queries the system wall-clock time.
2945 * This call is functionally equivalent to g_get_current_time() except
2946 * that the return value is often more convenient than dealing with a
2949 * You should only use this call if you are actually interested in the real
2950 * wall-clock time. g_get_monotonic_time() is probably more useful for
2951 * measuring intervals.
2953 * Returns: the number of microseconds since January 1, 1970 UTC.
2958 g_get_real_time (void)
2963 /* this is required on alpha, there the timeval structs are ints
2964 * not longs and a cast only would fail horribly */
2965 gettimeofday (&r, NULL);
2967 return (((gint64) r.tv_sec) * 1000000) + r.tv_usec;
2972 GetSystemTimeAsFileTime (&ft);
2973 memmove (&time64, &ft, sizeof (FILETIME));
2975 /* Convert from 100s of nanoseconds since 1601-01-01
2976 * to Unix epoch. This is Y2038 safe.
2978 time64 -= G_GINT64_CONSTANT (116444736000000000);
2986 * g_get_monotonic_time:
2988 * Queries the system monotonic time.
2990 * The monotonic clock will always increase and doesn't suffer
2991 * discontinuities when the user (or NTP) changes the system time. It
2992 * may or may not continue to tick during times where the machine is
2995 * We try to use the clock that corresponds as closely as possible to
2996 * the passage of time as measured by system calls such as poll() but it
2997 * may not always be possible to do this.
2999 * Returns: the monotonic time, in microseconds
3003 #if defined (G_OS_WIN32)
3005 * time_usec = ticks_since_boot * usec_per_sec / ticks_per_sec
3007 * Doing (ticks_since_boot * usec_per_sec) before the division can overflow 64 bits
3008 * (ticks_since_boot / ticks_per_sec) and then multiply would not be accurate enough.
3009 * So for now we calculate (usec_per_sec / ticks_per_sec) and use floating point
3011 static gdouble g_monotonic_usec_per_tick = 0;
3014 g_clock_win32_init (void)
3018 if (!QueryPerformanceFrequency (&freq) || freq.QuadPart == 0)
3020 /* The documentation says that this should never happen */
3021 g_assert_not_reached ();
3025 g_monotonic_usec_per_tick = (gdouble)G_USEC_PER_SEC / freq.QuadPart;
3029 g_get_monotonic_time (void)
3031 if (G_LIKELY (g_monotonic_usec_per_tick != 0))
3033 LARGE_INTEGER ticks;
3035 if (QueryPerformanceCounter (&ticks))
3036 return (gint64)(ticks.QuadPart * g_monotonic_usec_per_tick);
3038 g_warning ("QueryPerformanceCounter Failed (%lu)", GetLastError ());
3039 g_monotonic_usec_per_tick = 0;
3044 #elif defined(HAVE_MACH_MACH_TIME_H) /* Mac OS */
3046 g_get_monotonic_time (void)
3048 mach_timebase_info_data_t timebase_info;
3051 /* we get nanoseconds from mach_absolute_time() using timebase_info */
3052 mach_timebase_info (&timebase_info);
3053 val = mach_absolute_time ();
3055 if (timebase_info.numer != timebase_info.denom)
3057 #ifdef HAVE_UINT128_T
3058 val = ((__uint128_t) val * (__uint128_t) timebase_info.numer) / timebase_info.denom / 1000;
3060 guint64 t_high, t_low;
3061 guint64 result_high, result_low;
3063 /* 64 bit x 32 bit / 32 bit with 96-bit intermediate
3064 * algorithm lifted from qemu */
3065 t_low = (val & 0xffffffffLL) * (guint64) timebase_info.numer;
3066 t_high = (val >> 32) * (guint64) timebase_info.numer;
3067 t_high += (t_low >> 32);
3068 result_high = t_high / (guint64) timebase_info.denom;
3069 result_low = (((t_high % (guint64) timebase_info.denom) << 32) +
3070 (t_low & 0xffffffff)) /
3071 (guint64) timebase_info.denom;
3072 val = ((result_high << 32) | result_low) / 1000;
3077 /* nanoseconds to microseconds */
3085 g_get_monotonic_time (void)
3090 result = clock_gettime (CLOCK_MONOTONIC, &ts);
3092 if G_UNLIKELY (result != 0)
3093 g_error ("GLib requires working CLOCK_MONOTONIC");
3095 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
3100 g_main_dispatch_free (gpointer dispatch)
3105 /* Running the main loop */
3107 static GMainDispatch *
3110 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
3111 GMainDispatch *dispatch;
3113 dispatch = g_private_get (&depth_private);
3116 dispatch = g_private_set_alloc0 (&depth_private, sizeof (GMainDispatch));
3124 * Returns the depth of the stack of calls to
3125 * g_main_context_dispatch() on any #GMainContext in the current thread.
3126 * That is, when called from the toplevel, it gives 0. When
3127 * called from within a callback from g_main_context_iteration()
3128 * (or g_main_loop_run(), etc.) it returns 1. When called from within
3129 * a callback to a recursive call to g_main_context_iteration(),
3130 * it returns 2. And so forth.
3132 * This function is useful in a situation like the following:
3133 * Imagine an extremely simple "garbage collected" system.
3135 * |[<!-- language="C" -->
3136 * static GList *free_list;
3139 * allocate_memory (gsize size)
3141 * gpointer result = g_malloc (size);
3142 * free_list = g_list_prepend (free_list, result);
3147 * free_allocated_memory (void)
3150 * for (l = free_list; l; l = l->next);
3152 * g_list_free (free_list);
3160 * g_main_context_iteration (NULL, TRUE);
3161 * free_allocated_memory();
3165 * This works from an application, however, if you want to do the same
3166 * thing from a library, it gets more difficult, since you no longer
3167 * control the main loop. You might think you can simply use an idle
3168 * function to make the call to free_allocated_memory(), but that
3169 * doesn't work, since the idle function could be called from a
3170 * recursive callback. This can be fixed by using g_main_depth()
3172 * |[<!-- language="C" -->
3174 * allocate_memory (gsize size)
3176 * FreeListBlock *block = g_new (FreeListBlock, 1);
3177 * block->mem = g_malloc (size);
3178 * block->depth = g_main_depth ();
3179 * free_list = g_list_prepend (free_list, block);
3180 * return block->mem;
3184 * free_allocated_memory (void)
3188 * int depth = g_main_depth ();
3189 * for (l = free_list; l; );
3191 * GList *next = l->next;
3192 * FreeListBlock *block = l->data;
3193 * if (block->depth > depth)
3195 * g_free (block->mem);
3197 * free_list = g_list_delete_link (free_list, l);
3205 * There is a temptation to use g_main_depth() to solve
3206 * problems with reentrancy. For instance, while waiting for data
3207 * to be received from the network in response to a menu item,
3208 * the menu item might be selected again. It might seem that
3209 * one could make the menu item's callback return immediately
3210 * and do nothing if g_main_depth() returns a value greater than 1.
3211 * However, this should be avoided since the user then sees selecting
3212 * the menu item do nothing. Furthermore, you'll find yourself adding
3213 * these checks all over your code, since there are doubtless many,
3214 * many things that the user could do. Instead, you can use the
3215 * following techniques:
3217 * 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
3218 * the user from interacting with elements while the main
3219 * loop is recursing.
3221 * 2. Avoid main loop recursion in situations where you can't handle
3222 * arbitrary callbacks. Instead, structure your code so that you
3223 * simply return to the main loop and then get called again when
3224 * there is more work to do.
3226 * Returns: The main loop recursion level in the current thread
3231 GMainDispatch *dispatch = get_dispatch ();
3232 return dispatch->depth;
3236 * g_main_current_source:
3238 * Returns the currently firing source for this thread.
3240 * Returns: (transfer none) (nullable): The currently firing source or %NULL.
3245 g_main_current_source (void)
3247 GMainDispatch *dispatch = get_dispatch ();
3248 return dispatch->source;
3252 * g_source_is_destroyed:
3253 * @source: a #GSource
3255 * Returns whether @source has been destroyed.
3257 * This is important when you operate upon your objects
3258 * from within idle handlers, but may have freed the object
3259 * before the dispatch of your idle handler.
3261 * |[<!-- language="C" -->
3263 * idle_callback (gpointer data)
3265 * SomeWidget *self = data;
3267 * g_mutex_lock (&self->idle_id_mutex);
3268 * // do stuff with self
3269 * self->idle_id = 0;
3270 * g_mutex_unlock (&self->idle_id_mutex);
3272 * return G_SOURCE_REMOVE;
3276 * some_widget_do_stuff_later (SomeWidget *self)
3278 * g_mutex_lock (&self->idle_id_mutex);
3279 * self->idle_id = g_idle_add (idle_callback, self);
3280 * g_mutex_unlock (&self->idle_id_mutex);
3284 * some_widget_init (SomeWidget *self)
3286 * g_mutex_init (&self->idle_id_mutex);
3292 * some_widget_finalize (GObject *object)
3294 * SomeWidget *self = SOME_WIDGET (object);
3296 * if (self->idle_id)
3297 * g_source_remove (self->idle_id);
3299 * g_mutex_clear (&self->idle_id_mutex);
3301 * G_OBJECT_CLASS (parent_class)->finalize (object);
3305 * This will fail in a multi-threaded application if the
3306 * widget is destroyed before the idle handler fires due
3307 * to the use after free in the callback. A solution, to
3308 * this particular problem, is to check to if the source
3309 * has already been destroy within the callback.
3311 * |[<!-- language="C" -->
3313 * idle_callback (gpointer data)
3315 * SomeWidget *self = data;
3317 * g_mutex_lock (&self->idle_id_mutex);
3318 * if (!g_source_is_destroyed (g_main_current_source ()))
3320 * // do stuff with self
3322 * g_mutex_unlock (&self->idle_id_mutex);
3328 * Calls to this function from a thread other than the one acquired by the
3329 * #GMainContext the #GSource is attached to are typically redundant, as the
3330 * source could be destroyed immediately after this function returns. However,
3331 * once a source is destroyed it cannot be un-destroyed, so this function can be
3332 * used for opportunistic checks from any thread.
3334 * Returns: %TRUE if the source has been destroyed
3339 g_source_is_destroyed (GSource *source)
3341 g_return_val_if_fail (source != NULL, TRUE);
3342 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, TRUE);
3343 return SOURCE_DESTROYED (source);
3346 /* Temporarily remove all this source's file descriptors from the
3347 * poll(), so that if data comes available for one of the file descriptors
3348 * we don't continually spin in the poll()
3350 /* HOLDS: source->context's lock */
3352 block_source (GSource *source)
3356 g_return_if_fail (!SOURCE_BLOCKED (source));
3358 source->flags |= G_SOURCE_BLOCKED;
3360 if (source->context)
3362 tmp_list = source->poll_fds;
3365 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3366 tmp_list = tmp_list->next;
3369 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3370 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
3373 if (source->priv && source->priv->child_sources)
3375 tmp_list = source->priv->child_sources;
3378 block_source (tmp_list->data);
3379 tmp_list = tmp_list->next;
3384 /* HOLDS: source->context's lock */
3386 unblock_source (GSource *source)
3390 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
3391 g_return_if_fail (!SOURCE_DESTROYED (source));
3393 source->flags &= ~G_SOURCE_BLOCKED;
3395 tmp_list = source->poll_fds;
3398 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3399 tmp_list = tmp_list->next;
3402 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3403 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3405 if (source->priv && source->priv->child_sources)
3407 tmp_list = source->priv->child_sources;
3410 unblock_source (tmp_list->data);
3411 tmp_list = tmp_list->next;
3416 /* HOLDS: context's lock */
3418 g_main_dispatch (GMainContext *context)
3420 GMainDispatch *current = get_dispatch ();
3423 for (i = 0; i < context->pending_dispatches->len; i++)
3425 GSource *source = context->pending_dispatches->pdata[i];
3427 context->pending_dispatches->pdata[i] = NULL;
3430 source->flags &= ~G_SOURCE_READY;
3432 if (!SOURCE_DESTROYED (source))
3434 gboolean was_in_call;
3435 gpointer user_data = NULL;
3436 GSourceFunc callback = NULL;
3437 GSourceCallbackFuncs *cb_funcs;
3439 gboolean need_destroy;
3441 gboolean (*dispatch) (GSource *,
3444 GSource *prev_source;
3445 gint64 begin_time_nsec G_GNUC_UNUSED;
3447 dispatch = source->source_funcs->dispatch;
3448 cb_funcs = source->callback_funcs;
3449 cb_data = source->callback_data;
3452 cb_funcs->ref (cb_data);
3454 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3455 block_source (source);
3457 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3458 source->flags |= G_HOOK_FLAG_IN_CALL;
3461 cb_funcs->get (cb_data, source, &callback, &user_data);
3463 UNLOCK_CONTEXT (context);
3465 /* These operations are safe because 'current' is thread-local
3466 * and not modified from anywhere but this function.
3468 prev_source = current->source;
3469 current->source = source;
3472 begin_time_nsec = G_TRACE_CURRENT_TIME;
3474 TRACE (GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source), source,
3475 dispatch, callback, user_data));
3476 need_destroy = !(* dispatch) (source, callback, user_data);
3477 TRACE (GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source), source,
3478 dispatch, need_destroy));
3480 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3481 "GLib", "GSource.dispatch",
3483 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3484 need_destroy ? "destroy" : "keep");
3486 current->source = prev_source;
3490 cb_funcs->unref (cb_data);
3492 LOCK_CONTEXT (context);
3495 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3497 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3498 unblock_source (source);
3500 /* Note: this depends on the fact that we can't switch
3501 * sources from one main context to another
3503 if (need_destroy && !SOURCE_DESTROYED (source))
3505 g_assert (source->context == context);
3506 g_source_destroy_internal (source, context, TRUE);
3510 g_source_unref_internal (source, context, TRUE);
3513 g_ptr_array_set_size (context->pending_dispatches, 0);
3517 * g_main_context_acquire:
3518 * @context: (nullable): a #GMainContext (if %NULL, the global-default
3519 * main context will be used)
3521 * Tries to become the owner of the specified context.
3522 * If some other thread is the owner of the context,
3523 * returns %FALSE immediately. Ownership is properly
3524 * recursive: the owner can require ownership again
3525 * and will release ownership when g_main_context_release()
3526 * is called as many times as g_main_context_acquire().
3528 * You must be the owner of a context before you
3529 * can call g_main_context_prepare(), g_main_context_query(),
3530 * g_main_context_check(), g_main_context_dispatch(), g_main_context_release().
3532 * Since 2.76 @context can be %NULL to use the global-default
3535 * Returns: %TRUE if the operation succeeded, and
3536 * this thread is now the owner of @context.
3539 g_main_context_acquire (GMainContext *context)
3541 gboolean result = FALSE;
3543 if (context == NULL)
3544 context = g_main_context_default ();
3546 LOCK_CONTEXT (context);
3548 result = g_main_context_acquire_unlocked (context);
3550 UNLOCK_CONTEXT (context);
3556 g_main_context_acquire_unlocked (GMainContext *context)
3558 GThread *self = G_THREAD_SELF;
3560 if (!context->owner)
3562 context->owner = self;
3563 g_assert (context->owner_count == 0);
3564 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE /* success */));
3567 if (context->owner == self)
3569 context->owner_count++;
3574 TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, FALSE /* failure */));
3580 * g_main_context_release:
3581 * @context: (nullable): a #GMainContext (if %NULL, the global-default
3582 * main context will be used)
3584 * Releases ownership of a context previously acquired by this thread
3585 * with g_main_context_acquire(). If the context was acquired multiple
3586 * times, the ownership will be released only when g_main_context_release()
3587 * is called as many times as it was acquired.
3589 * You must have successfully acquired the context with
3590 * g_main_context_acquire() before you may call this function.
3593 g_main_context_release (GMainContext *context)
3595 if (context == NULL)
3596 context = g_main_context_default ();
3598 LOCK_CONTEXT (context);
3599 g_main_context_release_unlocked (context);
3600 UNLOCK_CONTEXT (context);
3604 g_main_context_release_unlocked (GMainContext *context)
3606 /* NOTE: We should also have the following assert here:
3607 * g_return_if_fail (context->owner == G_THREAD_SELF);
3608 * However, this breaks NetworkManager, which has been (non-compliantly but
3609 * apparently safely) releasing a #GMainContext from a thread which didn’t
3611 * Breaking that would be quite disruptive, so we won’t do that now. However,
3612 * GLib reserves the right to add that assertion in future, if doing so would
3613 * allow for optimisations or refactorings. By that point, NetworkManager will
3614 * have to have reworked its use of #GMainContext.
3616 * See: https://gitlab.gnome.org/GNOME/glib/-/merge_requests/3513
3618 g_return_if_fail (context->owner_count > 0);
3620 context->owner_count--;
3621 if (context->owner_count == 0)
3623 TRACE (GLIB_MAIN_CONTEXT_RELEASE (context));
3625 context->owner = NULL;
3627 if (context->waiters)
3629 GMainWaiter *waiter = context->waiters->data;
3630 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3631 context->waiters = g_slist_delete_link (context->waiters,
3633 if (!loop_internal_waiter)
3634 g_mutex_lock (waiter->mutex);
3636 g_cond_signal (waiter->cond);
3638 if (!loop_internal_waiter)
3639 g_mutex_unlock (waiter->mutex);
3645 g_main_context_wait_internal (GMainContext *context,
3649 gboolean result = FALSE;
3650 GThread *self = G_THREAD_SELF;
3651 gboolean loop_internal_waiter;
3653 loop_internal_waiter = (mutex == &context->mutex);
3655 if (!loop_internal_waiter)
3656 LOCK_CONTEXT (context);
3658 if (context->owner && context->owner != self)
3663 waiter.mutex = mutex;
3665 context->waiters = g_slist_append (context->waiters, &waiter);
3667 if (!loop_internal_waiter)
3668 UNLOCK_CONTEXT (context);
3669 g_cond_wait (cond, mutex);
3670 if (!loop_internal_waiter)
3671 LOCK_CONTEXT (context);
3673 context->waiters = g_slist_remove (context->waiters, &waiter);
3676 if (!context->owner)
3678 context->owner = self;
3679 g_assert (context->owner_count == 0);
3682 if (context->owner == self)
3684 context->owner_count++;
3688 if (!loop_internal_waiter)
3689 UNLOCK_CONTEXT (context);
3695 * g_main_context_wait:
3696 * @context: (nullable): a #GMainContext (if %NULL, the global-default
3697 * main context will be used)
3698 * @cond: a condition variable
3699 * @mutex: a mutex, currently held
3701 * Tries to become the owner of the specified context,
3702 * as with g_main_context_acquire(). But if another thread
3703 * is the owner, atomically drop @mutex and wait on @cond until
3704 * that owner releases ownership or until @cond is signaled, then
3705 * try again (once) to become the owner.
3707 * Returns: %TRUE if the operation succeeded, and
3708 * this thread is now the owner of @context.
3709 * Deprecated: 2.58: Use g_main_context_is_owner() and separate locking instead.
3712 g_main_context_wait (GMainContext *context,
3716 if (context == NULL)
3717 context = g_main_context_default ();
3719 if (G_UNLIKELY (cond != &context->cond || mutex != &context->mutex))
3721 static gboolean warned;
3725 g_critical ("WARNING!! g_main_context_wait() will be removed in a future release. "
3726 "If you see this message, please file a bug immediately.");
3731 return g_main_context_wait_internal (context, cond, mutex);
3735 * g_main_context_prepare:
3736 * @context: (nullable): a #GMainContext (if %NULL, the global-default
3737 * main context will be used)
3738 * @priority: (out) (optional): location to store priority of highest priority
3739 * source already ready.
3741 * Prepares to poll sources within a main loop. The resulting information
3742 * for polling is determined by calling g_main_context_query ().
3744 * You must have successfully acquired the context with
3745 * g_main_context_acquire() before you may call this function.
3747 * Returns: %TRUE if some source is ready to be dispatched
3751 g_main_context_prepare (GMainContext *context,
3756 if (context == NULL)
3757 context = g_main_context_default ();
3759 LOCK_CONTEXT (context);
3761 ready = g_main_context_prepare_unlocked (context, priority);
3763 UNLOCK_CONTEXT (context);
3769 g_main_context_prepare_unlocked (GMainContext *context,
3774 gint current_priority = G_MAXINT;
3778 context->time_is_fresh = FALSE;
3780 if (context->in_check_or_prepare)
3782 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3783 "prepare() member.");
3787 TRACE (GLIB_MAIN_CONTEXT_BEFORE_PREPARE (context));
3790 /* If recursing, finish up current dispatch, before starting over */
3791 if (context->pending_dispatches)
3794 g_main_dispatch (context, ¤t_time);
3800 /* If recursing, clear list of pending dispatches */
3802 for (i = 0; i < context->pending_dispatches->len; i++)
3804 if (context->pending_dispatches->pdata[i])
3805 g_source_unref_internal ((GSource *)context->pending_dispatches->pdata[i], context, TRUE);
3807 g_ptr_array_set_size (context->pending_dispatches, 0);
3809 /* Prepare all sources */
3811 context->timeout = -1;
3813 g_source_iter_init (&iter, context, TRUE);
3814 while (g_source_iter_next (&iter, &source))
3816 gint source_timeout = -1;
3818 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3820 if ((n_ready > 0) && (source->priority > current_priority))
3823 if (!(source->flags & G_SOURCE_READY))
3826 gboolean (* prepare) (GSource *source,
3829 prepare = source->source_funcs->prepare;
3833 gint64 begin_time_nsec G_GNUC_UNUSED;
3835 context->in_check_or_prepare++;
3836 UNLOCK_CONTEXT (context);
3838 begin_time_nsec = G_TRACE_CURRENT_TIME;
3840 result = (* prepare) (source, &source_timeout);
3841 TRACE (GLIB_MAIN_AFTER_PREPARE (source, prepare, source_timeout));
3843 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
3844 "GLib", "GSource.prepare",
3846 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
3847 result ? "ready" : "unready");
3849 LOCK_CONTEXT (context);
3850 context->in_check_or_prepare--;
3855 if (result == FALSE && source->priv->ready_time != -1)
3857 if (!context->time_is_fresh)
3859 context->time = g_get_monotonic_time ();
3860 context->time_is_fresh = TRUE;
3863 if (source->priv->ready_time <= context->time)
3872 /* rounding down will lead to spinning, so always round up */
3873 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3875 if (source_timeout < 0 || timeout < source_timeout)
3876 source_timeout = MIN (timeout, G_MAXINT);
3882 GSource *ready_source = source;
3884 while (ready_source)
3886 ready_source->flags |= G_SOURCE_READY;
3887 ready_source = ready_source->priv->parent_source;
3892 if (source->flags & G_SOURCE_READY)
3895 current_priority = source->priority;
3896 context->timeout = 0;
3899 if (source_timeout >= 0)
3901 if (context->timeout < 0)
3902 context->timeout = source_timeout;
3904 context->timeout = MIN (context->timeout, source_timeout);
3907 g_source_iter_clear (&iter);
3909 TRACE (GLIB_MAIN_CONTEXT_AFTER_PREPARE (context, current_priority, n_ready));
3912 *priority = current_priority;
3914 return (n_ready > 0);
3918 * g_main_context_query:
3919 * @context: (nullable): a #GMainContext (if %NULL, the global-default
3920 * main context will be used)
3921 * @max_priority: maximum priority source to check
3922 * @timeout_: (out): location to store timeout to be used in polling
3923 * @fds: (out caller-allocates) (array length=n_fds): location to
3924 * store #GPollFD records that need to be polled.
3925 * @n_fds: (in): length of @fds.
3927 * Determines information necessary to poll this main loop. You should
3928 * be careful to pass the resulting @fds array and its length @n_fds
3929 * as is when calling g_main_context_check(), as this function relies
3930 * on assumptions made when the array is filled.
3932 * You must have successfully acquired the context with
3933 * g_main_context_acquire() before you may call this function.
3935 * Returns: the number of records actually stored in @fds,
3936 * or, if more than @n_fds records need to be stored, the number
3937 * of records that need to be stored.
3940 g_main_context_query (GMainContext *context,
3948 if (context == NULL)
3949 context = g_main_context_default ();
3951 LOCK_CONTEXT (context);
3953 n_poll = g_main_context_query_unlocked (context, max_priority, timeout, fds, n_fds);
3955 UNLOCK_CONTEXT (context);
3961 g_main_context_query_unlocked (GMainContext *context,
3968 GPollRec *pollrec, *lastpollrec;
3971 TRACE (GLIB_MAIN_CONTEXT_BEFORE_QUERY (context, max_priority));
3973 /* fds is filled sequentially from poll_records. Since poll_records
3974 * are incrementally sorted by file descriptor identifier, fds will
3975 * also be incrementally sorted.
3979 for (pollrec = context->poll_records; pollrec; pollrec = pollrec->next)
3981 if (pollrec->priority > max_priority)
3984 /* In direct contradiction to the Unix98 spec, IRIX runs into
3985 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3986 * flags in the events field of the pollfd while it should
3987 * just ignoring them. So we mask them out here.
3989 events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3991 /* This optimization --using the same GPollFD to poll for more
3992 * than one poll record-- relies on the poll records being
3993 * incrementally sorted.
3995 if (lastpollrec && pollrec->fd->fd == lastpollrec->fd->fd)
3997 if (n_poll - 1 < n_fds)
3998 fds[n_poll - 1].events |= events;
4004 fds[n_poll].fd = pollrec->fd->fd;
4005 fds[n_poll].events = events;
4006 fds[n_poll].revents = 0;
4012 lastpollrec = pollrec;
4015 context->poll_changed = FALSE;
4019 *timeout = context->timeout;
4021 context->time_is_fresh = FALSE;
4024 TRACE (GLIB_MAIN_CONTEXT_AFTER_QUERY (context, context->timeout,
4031 * g_main_context_check:
4032 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4033 * main context will be used)
4034 * @max_priority: the maximum numerical priority of sources to check
4035 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
4036 * the last call to g_main_context_query()
4037 * @n_fds: return value of g_main_context_query()
4039 * Passes the results of polling back to the main loop. You should be
4040 * careful to pass @fds and its length @n_fds as received from
4041 * g_main_context_query(), as this functions relies on assumptions
4042 * on how @fds is filled.
4044 * You must have successfully acquired the context with
4045 * g_main_context_acquire() before you may call this function.
4047 * Since 2.76 @context can be %NULL to use the global-default
4050 * Returns: %TRUE if some sources are ready to be dispatched.
4053 g_main_context_check (GMainContext *context,
4060 LOCK_CONTEXT (context);
4062 ready = g_main_context_check_unlocked (context, max_priority, fds, n_fds);
4064 UNLOCK_CONTEXT (context);
4070 g_main_context_check_unlocked (GMainContext *context,
4081 if (context == NULL)
4082 context = g_main_context_default ();
4084 if (context->in_check_or_prepare)
4086 g_warning ("g_main_context_check() called recursively from within a source's check() or "
4087 "prepare() member.");
4091 TRACE (GLIB_MAIN_CONTEXT_BEFORE_CHECK (context, max_priority, fds, n_fds));
4093 for (i = 0; i < n_fds; i++)
4095 if (fds[i].fd == context->wake_up_rec.fd)
4099 TRACE (GLIB_MAIN_CONTEXT_WAKEUP_ACKNOWLEDGE (context));
4100 g_wakeup_acknowledge (context->wakeup);
4106 /* If the set of poll file descriptors changed, bail out
4107 * and let the main loop rerun
4109 if (context->poll_changed)
4111 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, 0));
4116 /* The linear iteration below relies on the assumption that both
4117 * poll records and the fds array are incrementally sorted by file
4118 * descriptor identifier.
4120 pollrec = context->poll_records;
4122 while (pollrec && i < n_fds)
4124 /* Make sure that fds is sorted by file descriptor identifier. */
4125 g_assert (i <= 0 || fds[i - 1].fd < fds[i].fd);
4127 /* Skip until finding the first GPollRec matching the current GPollFD. */
4128 while (pollrec && pollrec->fd->fd != fds[i].fd)
4129 pollrec = pollrec->next;
4131 /* Update all consecutive GPollRecs that match. */
4132 while (pollrec && pollrec->fd->fd == fds[i].fd)
4134 if (pollrec->priority <= max_priority)
4136 pollrec->fd->revents =
4137 fds[i].revents & (pollrec->fd->events | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
4139 pollrec = pollrec->next;
4142 /* Iterate to next GPollFD. */
4146 g_source_iter_init (&iter, context, TRUE);
4147 while (g_source_iter_next (&iter, &source))
4149 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
4151 if ((n_ready > 0) && (source->priority > max_priority))
4154 if (!(source->flags & G_SOURCE_READY))
4157 gboolean (* check) (GSource *source);
4159 check = source->source_funcs->check;
4163 gint64 begin_time_nsec G_GNUC_UNUSED;
4165 /* If the check function is set, call it. */
4166 context->in_check_or_prepare++;
4167 UNLOCK_CONTEXT (context);
4169 begin_time_nsec = G_TRACE_CURRENT_TIME;
4171 result = (* check) (source);
4173 TRACE (GLIB_MAIN_AFTER_CHECK (source, check, result));
4175 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
4176 "GLib", "GSource.check",
4178 (g_source_get_name (source) != NULL) ? g_source_get_name (source) : "(unnamed)",
4179 result ? "dispatch" : "ignore");
4181 LOCK_CONTEXT (context);
4182 context->in_check_or_prepare--;
4187 if (result == FALSE)
4191 /* If not already explicitly flagged ready by ->check()
4192 * (or if we have no check) then we can still be ready if
4193 * any of our fds poll as ready.
4195 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
4197 GPollFD *pollfd = tmp_list->data;
4199 if (pollfd->revents)
4207 if (result == FALSE && source->priv->ready_time != -1)
4209 if (!context->time_is_fresh)
4211 context->time = g_get_monotonic_time ();
4212 context->time_is_fresh = TRUE;
4215 if (source->priv->ready_time <= context->time)
4221 GSource *ready_source = source;
4223 while (ready_source)
4225 ready_source->flags |= G_SOURCE_READY;
4226 ready_source = ready_source->priv->parent_source;
4231 if (source->flags & G_SOURCE_READY)
4233 g_source_ref (source);
4234 g_ptr_array_add (context->pending_dispatches, source);
4238 /* never dispatch sources with less priority than the first
4239 * one we choose to dispatch
4241 max_priority = source->priority;
4244 g_source_iter_clear (&iter);
4246 TRACE (GLIB_MAIN_CONTEXT_AFTER_CHECK (context, n_ready));
4252 * g_main_context_dispatch:
4253 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4254 * main context will be used)
4256 * Dispatches all pending sources.
4258 * You must have successfully acquired the context with
4259 * g_main_context_acquire() before you may call this function.
4261 * Since 2.76 @context can be %NULL to use the global-default
4265 g_main_context_dispatch (GMainContext *context)
4267 if (context == NULL)
4268 context = g_main_context_default ();
4270 LOCK_CONTEXT (context);
4272 g_main_context_dispatch_unlocked (context);
4274 UNLOCK_CONTEXT (context);
4278 g_main_context_dispatch_unlocked (GMainContext *context)
4280 TRACE (GLIB_MAIN_CONTEXT_BEFORE_DISPATCH (context));
4282 if (context->pending_dispatches->len > 0)
4284 g_main_dispatch (context);
4287 TRACE (GLIB_MAIN_CONTEXT_AFTER_DISPATCH (context));
4290 /* HOLDS context lock */
4292 g_main_context_iterate_unlocked (GMainContext *context,
4297 gint max_priority = 0;
4299 gboolean some_ready;
4300 gint nfds, allocated_nfds;
4301 GPollFD *fds = NULL;
4302 gint64 begin_time_nsec G_GNUC_UNUSED;
4304 begin_time_nsec = G_TRACE_CURRENT_TIME;
4306 if (!g_main_context_acquire_unlocked (context))
4308 gboolean got_ownership;
4313 got_ownership = g_main_context_wait_internal (context,
4321 if (!context->cached_poll_array)
4323 context->cached_poll_array_size = context->n_poll_records;
4324 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
4327 allocated_nfds = context->cached_poll_array_size;
4328 fds = context->cached_poll_array;
4330 g_main_context_prepare_unlocked (context, &max_priority);
4332 while ((nfds = g_main_context_query_unlocked (
4333 context, max_priority, &timeout, fds,
4334 allocated_nfds)) > allocated_nfds)
4337 context->cached_poll_array_size = allocated_nfds = nfds;
4338 context->cached_poll_array = fds = g_new (GPollFD, nfds);
4344 g_main_context_poll_unlocked (context, timeout, max_priority, fds, nfds);
4346 some_ready = g_main_context_check_unlocked (context, max_priority, fds, nfds);
4349 g_main_context_dispatch_unlocked (context);
4351 g_main_context_release_unlocked (context);
4353 g_trace_mark (begin_time_nsec, G_TRACE_CURRENT_TIME - begin_time_nsec,
4354 "GLib", "g_main_context_iterate",
4355 "Context %p, %s ⇒ %s", context, block ? "blocking" : "non-blocking", some_ready ? "dispatched" : "nothing");
4361 * g_main_context_pending:
4362 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4363 * main context will be used)
4365 * Checks if any sources have pending events for the given context.
4367 * Returns: %TRUE if events are pending.
4370 g_main_context_pending (GMainContext *context)
4375 context = g_main_context_default();
4377 LOCK_CONTEXT (context);
4378 retval = g_main_context_iterate_unlocked (context, FALSE, FALSE, G_THREAD_SELF);
4379 UNLOCK_CONTEXT (context);
4385 * g_main_context_iteration:
4386 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4387 * main context will be used)
4388 * @may_block: whether the call may block.
4390 * Runs a single iteration for the given main loop. This involves
4391 * checking to see if any event sources are ready to be processed,
4392 * then if no events sources are ready and @may_block is %TRUE, waiting
4393 * for a source to become ready, then dispatching the highest priority
4394 * events sources that are ready. Otherwise, if @may_block is %FALSE
4395 * sources are not waited to become ready, only those highest priority
4396 * events sources will be dispatched (if any), that are ready at this
4397 * given moment without further waiting.
4399 * Note that even when @may_block is %TRUE, it is still possible for
4400 * g_main_context_iteration() to return %FALSE, since the wait may
4401 * be interrupted for other reasons than an event source becoming ready.
4403 * Returns: %TRUE if events were dispatched.
4406 g_main_context_iteration (GMainContext *context, gboolean may_block)
4411 context = g_main_context_default();
4413 LOCK_CONTEXT (context);
4414 retval = g_main_context_iterate_unlocked (context, may_block, TRUE, G_THREAD_SELF);
4415 UNLOCK_CONTEXT (context);
4422 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4423 * main context will be used).
4424 * @is_running: set to %TRUE to indicate that the loop is running. This
4425 * is not very important since calling g_main_loop_run() will set this to
4428 * Creates a new #GMainLoop structure.
4430 * Returns: a new #GMainLoop.
4433 g_main_loop_new (GMainContext *context,
4434 gboolean is_running)
4439 context = g_main_context_default();
4441 g_main_context_ref (context);
4443 loop = g_new0 (GMainLoop, 1);
4444 loop->context = context;
4445 loop->is_running = is_running != FALSE;
4446 loop->ref_count = 1;
4448 TRACE (GLIB_MAIN_LOOP_NEW (loop, context));
4455 * @loop: a #GMainLoop
4457 * Increases the reference count on a #GMainLoop object by one.
4462 g_main_loop_ref (GMainLoop *loop)
4464 g_return_val_if_fail (loop != NULL, NULL);
4465 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4467 g_atomic_int_inc (&loop->ref_count);
4473 * g_main_loop_unref:
4474 * @loop: a #GMainLoop
4476 * Decreases the reference count on a #GMainLoop object by one. If
4477 * the result is zero, free the loop and free all associated memory.
4480 g_main_loop_unref (GMainLoop *loop)
4482 g_return_if_fail (loop != NULL);
4483 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4485 if (!g_atomic_int_dec_and_test (&loop->ref_count))
4488 g_main_context_unref (loop->context);
4494 * @loop: a #GMainLoop
4496 * Runs a main loop until g_main_loop_quit() is called on the loop.
4497 * If this is called for the thread of the loop's #GMainContext,
4498 * it will process events from the loop, otherwise it will
4502 g_main_loop_run (GMainLoop *loop)
4504 GThread *self = G_THREAD_SELF;
4506 g_return_if_fail (loop != NULL);
4507 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4509 /* Hold a reference in case the loop is unreffed from a callback function */
4510 g_atomic_int_inc (&loop->ref_count);
4512 LOCK_CONTEXT (loop->context);
4514 if (!g_main_context_acquire_unlocked (loop->context))
4516 gboolean got_ownership = FALSE;
4518 /* Another thread owns this context */
4519 g_atomic_int_set (&loop->is_running, TRUE);
4521 while (g_atomic_int_get (&loop->is_running) && !got_ownership)
4522 got_ownership = g_main_context_wait_internal (loop->context,
4523 &loop->context->cond,
4524 &loop->context->mutex);
4526 if (!g_atomic_int_get (&loop->is_running))
4529 g_main_context_release_unlocked (loop->context);
4531 UNLOCK_CONTEXT (loop->context);
4532 g_main_loop_unref (loop);
4536 g_assert (got_ownership);
4539 if G_UNLIKELY (loop->context->in_check_or_prepare)
4541 g_warning ("g_main_loop_run(): called recursively from within a source's "
4542 "check() or prepare() member, iteration not possible.");
4543 g_main_context_release_unlocked (loop->context);
4544 UNLOCK_CONTEXT (loop->context);
4545 g_main_loop_unref (loop);
4549 g_atomic_int_set (&loop->is_running, TRUE);
4550 while (g_atomic_int_get (&loop->is_running))
4551 g_main_context_iterate_unlocked (loop->context, TRUE, TRUE, self);
4553 g_main_context_release_unlocked (loop->context);
4555 UNLOCK_CONTEXT (loop->context);
4557 g_main_loop_unref (loop);
4562 * @loop: a #GMainLoop
4564 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
4565 * for the loop will return.
4567 * Note that sources that have already been dispatched when
4568 * g_main_loop_quit() is called will still be executed.
4571 g_main_loop_quit (GMainLoop *loop)
4573 g_return_if_fail (loop != NULL);
4574 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
4576 LOCK_CONTEXT (loop->context);
4577 g_atomic_int_set (&loop->is_running, FALSE);
4578 g_wakeup_signal (loop->context->wakeup);
4580 g_cond_broadcast (&loop->context->cond);
4582 UNLOCK_CONTEXT (loop->context);
4584 TRACE (GLIB_MAIN_LOOP_QUIT (loop));
4588 * g_main_loop_is_running:
4589 * @loop: a #GMainLoop.
4591 * Checks to see if the main loop is currently being run via g_main_loop_run().
4593 * Returns: %TRUE if the mainloop is currently being run.
4596 g_main_loop_is_running (GMainLoop *loop)
4598 g_return_val_if_fail (loop != NULL, FALSE);
4599 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
4601 return g_atomic_int_get (&loop->is_running);
4605 * g_main_loop_get_context:
4606 * @loop: a #GMainLoop.
4608 * Returns the #GMainContext of @loop.
4610 * Returns: (transfer none): the #GMainContext of @loop
4613 g_main_loop_get_context (GMainLoop *loop)
4615 g_return_val_if_fail (loop != NULL, NULL);
4616 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
4618 return loop->context;
4621 /* HOLDS: context's lock */
4623 g_main_context_poll_unlocked (GMainContext *context,
4629 #ifdef G_MAIN_POLL_DEBUG
4635 GPollFunc poll_func;
4637 if (n_fds || timeout != 0)
4641 #ifdef G_MAIN_POLL_DEBUG
4643 if (_g_main_poll_debug)
4645 g_print ("polling context=%p n=%d timeout=%d\n",
4646 context, n_fds, timeout);
4647 poll_timer = g_timer_new ();
4650 poll_func = context->poll_func;
4652 UNLOCK_CONTEXT (context);
4653 ret = (*poll_func) (fds, n_fds, timeout);
4654 LOCK_CONTEXT (context);
4657 if (ret < 0 && errsv != EINTR)
4660 g_warning ("poll(2) failed due to: %s.",
4661 g_strerror (errsv));
4663 /* If g_poll () returns -1, it has already called g_warning() */
4667 #ifdef G_MAIN_POLL_DEBUG
4668 if (_g_main_poll_debug)
4670 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4673 g_timer_elapsed (poll_timer, NULL));
4674 g_timer_destroy (poll_timer);
4675 pollrec = context->poll_records;
4677 while (pollrec != NULL)
4682 if (fds[i].fd == pollrec->fd->fd &&
4683 pollrec->fd->events &&
4686 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4687 if (fds[i].revents & G_IO_IN)
4689 if (fds[i].revents & G_IO_OUT)
4691 if (fds[i].revents & G_IO_PRI)
4693 if (fds[i].revents & G_IO_ERR)
4695 if (fds[i].revents & G_IO_HUP)
4697 if (fds[i].revents & G_IO_NVAL)
4703 pollrec = pollrec->next;
4708 } /* if (n_fds || timeout != 0) */
4712 * g_main_context_add_poll:
4713 * @context: (nullable): a #GMainContext (or %NULL for the global-default
4715 * @fd: a #GPollFD structure holding information about a file
4716 * descriptor to watch.
4717 * @priority: the priority for this file descriptor which should be
4718 * the same as the priority used for g_source_attach() to ensure that the
4719 * file descriptor is polled whenever the results may be needed.
4721 * Adds a file descriptor to the set of file descriptors polled for
4722 * this context. This will very seldom be used directly. Instead
4723 * a typical event source will use g_source_add_unix_fd() instead.
4726 g_main_context_add_poll (GMainContext *context,
4731 context = g_main_context_default ();
4733 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4734 g_return_if_fail (fd);
4736 LOCK_CONTEXT (context);
4737 g_main_context_add_poll_unlocked (context, priority, fd);
4738 UNLOCK_CONTEXT (context);
4741 /* HOLDS: main_loop_lock */
4743 g_main_context_add_poll_unlocked (GMainContext *context,
4747 GPollRec *prevrec, *nextrec;
4748 GPollRec *newrec = g_slice_new (GPollRec);
4750 /* This file descriptor may be checked before we ever poll */
4753 newrec->priority = priority;
4755 /* Poll records are incrementally sorted by file descriptor identifier. */
4757 nextrec = context->poll_records;
4760 if (nextrec->fd->fd > fd->fd)
4763 nextrec = nextrec->next;
4767 prevrec->next = newrec;
4769 context->poll_records = newrec;
4771 newrec->prev = prevrec;
4772 newrec->next = nextrec;
4775 nextrec->prev = newrec;
4777 context->n_poll_records++;
4779 context->poll_changed = TRUE;
4781 /* Now wake up the main loop if it is waiting in the poll() */
4782 if (fd != &context->wake_up_rec)
4783 g_wakeup_signal (context->wakeup);
4787 * g_main_context_remove_poll:
4788 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4789 * main context will be used)
4790 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4792 * Removes file descriptor from the set of file descriptors to be
4793 * polled for a particular context.
4796 g_main_context_remove_poll (GMainContext *context,
4800 context = g_main_context_default ();
4802 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4803 g_return_if_fail (fd);
4805 LOCK_CONTEXT (context);
4806 g_main_context_remove_poll_unlocked (context, fd);
4807 UNLOCK_CONTEXT (context);
4811 g_main_context_remove_poll_unlocked (GMainContext *context,
4814 GPollRec *pollrec, *prevrec, *nextrec;
4817 pollrec = context->poll_records;
4821 nextrec = pollrec->next;
4822 if (pollrec->fd == fd)
4824 if (prevrec != NULL)
4825 prevrec->next = nextrec;
4827 context->poll_records = nextrec;
4829 if (nextrec != NULL)
4830 nextrec->prev = prevrec;
4832 g_slice_free (GPollRec, pollrec);
4834 context->n_poll_records--;
4841 context->poll_changed = TRUE;
4843 /* Now wake up the main loop if it is waiting in the poll() */
4844 g_wakeup_signal (context->wakeup);
4848 * g_source_get_current_time:
4849 * @source: a #GSource
4850 * @timeval: #GTimeVal structure in which to store current time.
4852 * This function ignores @source and is otherwise the same as
4853 * g_get_current_time().
4855 * Deprecated: 2.28: use g_source_get_time() instead
4857 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4859 g_source_get_current_time (GSource *source,
4862 g_get_current_time (timeval);
4864 G_GNUC_END_IGNORE_DEPRECATIONS
4867 * g_source_get_time:
4868 * @source: a #GSource
4870 * Gets the time to be used when checking this source. The advantage of
4871 * calling this function over calling g_get_monotonic_time() directly is
4872 * that when checking multiple sources, GLib can cache a single value
4873 * instead of having to repeatedly get the system monotonic time.
4875 * The time here is the system monotonic time, if available, or some
4876 * other reasonable alternative otherwise. See g_get_monotonic_time().
4878 * Returns: the monotonic time in microseconds
4883 g_source_get_time (GSource *source)
4885 GMainContext *context;
4888 g_return_val_if_fail (source != NULL, 0);
4889 g_return_val_if_fail (g_atomic_int_get (&source->ref_count) > 0, 0);
4890 g_return_val_if_fail (source->context != NULL, 0);
4892 context = source->context;
4894 LOCK_CONTEXT (context);
4896 if (!context->time_is_fresh)
4898 context->time = g_get_monotonic_time ();
4899 context->time_is_fresh = TRUE;
4902 result = context->time;
4904 UNLOCK_CONTEXT (context);
4910 * g_main_context_set_poll_func:
4911 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4912 * main context will be used)
4913 * @func: the function to call to poll all file descriptors
4915 * Sets the function to use to handle polling of file descriptors. It
4916 * will be used instead of the poll() system call
4917 * (or GLib's replacement function, which is used where
4918 * poll() isn't available).
4920 * This function could possibly be used to integrate the GLib event
4921 * loop with an external event loop.
4924 g_main_context_set_poll_func (GMainContext *context,
4928 context = g_main_context_default ();
4930 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4932 LOCK_CONTEXT (context);
4935 context->poll_func = func;
4937 context->poll_func = g_poll;
4939 UNLOCK_CONTEXT (context);
4943 * g_main_context_get_poll_func:
4944 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4945 * main context will be used)
4947 * Gets the poll function set by g_main_context_set_poll_func().
4949 * Returns: the poll function
4952 g_main_context_get_poll_func (GMainContext *context)
4957 context = g_main_context_default ();
4959 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4961 LOCK_CONTEXT (context);
4962 result = context->poll_func;
4963 UNLOCK_CONTEXT (context);
4969 * g_main_context_wakeup:
4970 * @context: (nullable): a #GMainContext (if %NULL, the global-default
4971 * main context will be used)
4973 * If @context is currently blocking in g_main_context_iteration()
4974 * waiting for a source to become ready, cause it to stop blocking
4975 * and return. Otherwise, cause the next invocation of
4976 * g_main_context_iteration() to return without blocking.
4978 * This API is useful for low-level control over #GMainContext; for
4979 * example, integrating it with main loop implementations such as
4982 * Another related use for this function is when implementing a main
4983 * loop with a termination condition, computed from multiple threads:
4985 * |[<!-- language="C" -->
4986 * #define NUM_TASKS 10
4987 * static gint tasks_remaining = NUM_TASKS; // (atomic)
4990 * while (g_atomic_int_get (&tasks_remaining) != 0)
4991 * g_main_context_iteration (NULL, TRUE);
4995 * |[<!-- language="C" -->
4998 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4999 * g_main_context_wakeup (NULL);
5003 g_main_context_wakeup (GMainContext *context)
5006 context = g_main_context_default ();
5008 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
5010 TRACE (GLIB_MAIN_CONTEXT_WAKEUP (context));
5012 g_wakeup_signal (context->wakeup);
5016 * g_main_context_is_owner:
5017 * @context: (nullable): a #GMainContext (if %NULL, the global-default
5018 * main context will be used)
5020 * Determines whether this thread holds the (recursive)
5021 * ownership of this #GMainContext. This is useful to
5022 * know before waiting on another thread that may be
5023 * blocking to get ownership of @context.
5025 * Returns: %TRUE if current thread is owner of @context.
5030 g_main_context_is_owner (GMainContext *context)
5035 context = g_main_context_default ();
5037 LOCK_CONTEXT (context);
5038 is_owner = context->owner == G_THREAD_SELF;
5039 UNLOCK_CONTEXT (context);
5047 g_timeout_set_expiration (GTimeoutSource *timeout_source,
5048 gint64 current_time)
5052 if (timeout_source->seconds)
5055 static gint timer_perturb = -1;
5057 if (timer_perturb == -1)
5060 * we want a per machine/session unique 'random' value; try the dbus
5061 * address first, that has a UUID in it. If there is no dbus, use the
5062 * hostname for hashing.
5064 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
5065 if (!session_bus_address)
5066 session_bus_address = g_getenv ("HOSTNAME");
5067 if (session_bus_address)
5068 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
5073 expiration = current_time + (guint64) timeout_source->interval * 1000 * 1000;
5075 /* We want the microseconds part of the timeout to land on the
5076 * 'timer_perturb' mark, but we need to make sure we don't try to
5077 * set the timeout in the past. We do this by ensuring that we
5078 * always only *increase* the expiration time by adding a full
5079 * second in the case that the microsecond portion decreases.
5081 expiration -= timer_perturb;
5083 remainder = expiration % 1000000;
5084 if (remainder >= 1000000/4)
5085 expiration += 1000000;
5087 expiration -= remainder;
5088 expiration += timer_perturb;
5092 expiration = current_time + (guint64) timeout_source->interval * 1000;
5095 g_source_set_ready_time ((GSource *) timeout_source, expiration);
5099 g_timeout_dispatch (GSource *source,
5100 GSourceFunc callback,
5103 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
5108 g_warning ("Timeout source dispatched without callback. "
5109 "You must call g_source_set_callback().");
5113 if (timeout_source->one_shot)
5115 GSourceOnceFunc once_callback = (GSourceOnceFunc) callback;
5116 once_callback (user_data);
5117 again = G_SOURCE_REMOVE;
5121 again = callback (user_data);
5124 TRACE (GLIB_TIMEOUT_DISPATCH (source, source->context, callback, user_data, again));
5127 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
5133 timeout_source_new (guint interval,
5137 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
5138 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
5140 timeout_source->interval = interval;
5141 timeout_source->seconds = seconds;
5142 timeout_source->one_shot = one_shot;
5144 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
5150 * g_timeout_source_new:
5151 * @interval: the timeout interval in milliseconds.
5153 * Creates a new timeout source.
5155 * The source will not initially be associated with any #GMainContext
5156 * and must be added to one with g_source_attach() before it will be
5159 * The interval given is in terms of monotonic time, not wall clock
5160 * time. See g_get_monotonic_time().
5162 * Returns: the newly-created timeout source
5165 g_timeout_source_new (guint interval)
5167 return timeout_source_new (interval, FALSE, FALSE);
5171 * g_timeout_source_new_seconds:
5172 * @interval: the timeout interval in seconds
5174 * Creates a new timeout source.
5176 * The source will not initially be associated with any #GMainContext
5177 * and must be added to one with g_source_attach() before it will be
5180 * The scheduling granularity/accuracy of this timeout source will be
5183 * The interval given is in terms of monotonic time, not wall clock time.
5184 * See g_get_monotonic_time().
5186 * Returns: the newly-created timeout source
5191 g_timeout_source_new_seconds (guint interval)
5193 return timeout_source_new (interval, TRUE, FALSE);
5197 timeout_add_full (gint priority,
5201 GSourceFunc function,
5203 GDestroyNotify notify)
5208 g_return_val_if_fail (function != NULL, 0);
5210 source = timeout_source_new (interval, seconds, one_shot);
5212 if (priority != G_PRIORITY_DEFAULT)
5213 g_source_set_priority (source, priority);
5215 g_source_set_callback (source, function, data, notify);
5216 id = g_source_attach (source, NULL);
5218 TRACE (GLIB_TIMEOUT_ADD (source, g_main_context_default (), id, priority, interval, function, data));
5220 g_source_unref (source);
5226 * g_timeout_add_full: (rename-to g_timeout_add)
5227 * @priority: the priority of the timeout source. Typically this will be in
5228 * the range between %G_PRIORITY_DEFAULT and %G_PRIORITY_HIGH.
5229 * @interval: the time between calls to the function, in milliseconds
5230 * (1/1000ths of a second)
5231 * @function: function to call
5232 * @data: data to pass to @function
5233 * @notify: (nullable): function to call when the timeout is removed, or %NULL
5235 * Sets a function to be called at regular intervals, with the given
5236 * priority. The function is called repeatedly until it returns
5237 * %FALSE, at which point the timeout is automatically destroyed and
5238 * the function will not be called again. The @notify function is
5239 * called when the timeout is destroyed. The first call to the
5240 * function will be at the end of the first @interval.
5242 * Note that timeout functions may be delayed, due to the processing of other
5243 * event sources. Thus they should not be relied on for precise timing.
5244 * After each call to the timeout function, the time of the next
5245 * timeout is recalculated based on the current time and the given interval
5246 * (it does not try to 'catch up' time lost in delays).
5248 * See [memory management of sources][mainloop-memory-management] for details
5249 * on how to handle the return value and memory management of @data.
5251 * This internally creates a main loop source using g_timeout_source_new()
5252 * and attaches it to the global #GMainContext using g_source_attach(), so
5253 * the callback will be invoked in whichever thread is running that main
5254 * context. You can do these steps manually if you need greater control or to
5255 * use a custom main context.
5257 * The interval given is in terms of monotonic time, not wall clock time.
5258 * See g_get_monotonic_time().
5260 * Returns: the ID (greater than 0) of the event source.
5263 g_timeout_add_full (gint priority,
5265 GSourceFunc function,
5267 GDestroyNotify notify)
5269 return timeout_add_full (priority, interval, FALSE, FALSE, function, data, notify);
5274 * @interval: the time between calls to the function, in milliseconds
5275 * (1/1000ths of a second)
5276 * @function: function to call
5277 * @data: data to pass to @function
5279 * Sets a function to be called at regular intervals, with the default
5280 * priority, %G_PRIORITY_DEFAULT.
5282 * The given @function is called repeatedly until it returns %G_SOURCE_REMOVE
5283 * or %FALSE, at which point the timeout is automatically destroyed and the
5284 * function will not be called again. The first call to the function will be
5285 * at the end of the first @interval.
5287 * Note that timeout functions may be delayed, due to the processing of other
5288 * event sources. Thus they should not be relied on for precise timing.
5289 * After each call to the timeout function, the time of the next
5290 * timeout is recalculated based on the current time and the given interval
5291 * (it does not try to 'catch up' time lost in delays).
5293 * See [memory management of sources][mainloop-memory-management] for details
5294 * on how to handle the return value and memory management of @data.
5296 * If you want to have a timer in the "seconds" range and do not care
5297 * about the exact time of the first call of the timer, use the
5298 * g_timeout_add_seconds() function; this function allows for more
5299 * optimizations and more efficient system power usage.
5301 * This internally creates a main loop source using g_timeout_source_new()
5302 * and attaches it to the global #GMainContext using g_source_attach(), so
5303 * the callback will be invoked in whichever thread is running that main
5304 * context. You can do these steps manually if you need greater control or to
5305 * use a custom main context.
5307 * It is safe to call this function from any thread.
5309 * The interval given is in terms of monotonic time, not wall clock
5310 * time. See g_get_monotonic_time().
5312 * Returns: the ID (greater than 0) of the event source.
5315 g_timeout_add (guint32 interval,
5316 GSourceFunc function,
5319 return g_timeout_add_full (G_PRIORITY_DEFAULT,
5320 interval, function, data, NULL);
5324 * g_timeout_add_once:
5325 * @interval: the time after which the function will be called, in
5326 * milliseconds (1/1000ths of a second)
5327 * @function: function to call
5328 * @data: data to pass to @function
5330 * Sets a function to be called after @interval milliseconds have elapsed,
5331 * with the default priority, %G_PRIORITY_DEFAULT.
5333 * The given @function is called once and then the source will be automatically
5334 * removed from the main context.
5336 * This function otherwise behaves like g_timeout_add().
5338 * Returns: the ID (greater than 0) of the event source
5343 g_timeout_add_once (guint32 interval,
5344 GSourceOnceFunc function,
5347 return timeout_add_full (G_PRIORITY_DEFAULT, interval, FALSE, TRUE, (GSourceFunc) function, data, NULL);
5351 * g_timeout_add_seconds_full: (rename-to g_timeout_add_seconds)
5352 * @priority: the priority of the timeout source. Typically this will be in
5353 * the range between %G_PRIORITY_DEFAULT and %G_PRIORITY_HIGH.
5354 * @interval: the time between calls to the function, in seconds
5355 * @function: function to call
5356 * @data: data to pass to @function
5357 * @notify: (nullable): function to call when the timeout is removed, or %NULL
5359 * Sets a function to be called at regular intervals, with @priority.
5361 * The function is called repeatedly until it returns %G_SOURCE_REMOVE
5362 * or %FALSE, at which point the timeout is automatically destroyed and
5363 * the function will not be called again.
5365 * Unlike g_timeout_add(), this function operates at whole second granularity.
5366 * The initial starting point of the timer is determined by the implementation
5367 * and the implementation is expected to group multiple timers together so that
5368 * they fire all at the same time. To allow this grouping, the @interval to the
5369 * first timer is rounded and can deviate up to one second from the specified
5370 * interval. Subsequent timer iterations will generally run at the specified
5373 * Note that timeout functions may be delayed, due to the processing of other
5374 * event sources. Thus they should not be relied on for precise timing.
5375 * After each call to the timeout function, the time of the next
5376 * timeout is recalculated based on the current time and the given @interval
5378 * See [memory management of sources][mainloop-memory-management] for details
5379 * on how to handle the return value and memory management of @data.
5381 * If you want timing more precise than whole seconds, use g_timeout_add()
5384 * The grouping of timers to fire at the same time results in a more power
5385 * and CPU efficient behavior so if your timer is in multiples of seconds
5386 * and you don't require the first timer exactly one second from now, the
5387 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
5389 * This internally creates a main loop source using
5390 * g_timeout_source_new_seconds() and attaches it to the main loop context
5391 * using g_source_attach(). You can do these steps manually if you need
5394 * It is safe to call this function from any thread.
5396 * The interval given is in terms of monotonic time, not wall clock
5397 * time. See g_get_monotonic_time().
5399 * Returns: the ID (greater than 0) of the event source.
5404 g_timeout_add_seconds_full (gint priority,
5406 GSourceFunc function,
5408 GDestroyNotify notify)
5410 return timeout_add_full (priority, interval, TRUE, FALSE, function, data, notify);
5414 * g_timeout_add_seconds:
5415 * @interval: the time between calls to the function, in seconds
5416 * @function: function to call
5417 * @data: data to pass to @function
5419 * Sets a function to be called at regular intervals with the default
5420 * priority, %G_PRIORITY_DEFAULT.
5422 * The function is called repeatedly until it returns %G_SOURCE_REMOVE
5423 * or %FALSE, at which point the timeout is automatically destroyed
5424 * and the function will not be called again.
5426 * This internally creates a main loop source using
5427 * g_timeout_source_new_seconds() and attaches it to the main loop context
5428 * using g_source_attach(). You can do these steps manually if you need
5429 * greater control. Also see g_timeout_add_seconds_full().
5431 * It is safe to call this function from any thread.
5433 * Note that the first call of the timer may not be precise for timeouts
5434 * of one second. If you need finer precision and have such a timeout,
5435 * you may want to use g_timeout_add() instead.
5437 * See [memory management of sources][mainloop-memory-management] for details
5438 * on how to handle the return value and memory management of @data.
5440 * The interval given is in terms of monotonic time, not wall clock
5441 * time. See g_get_monotonic_time().
5443 * Returns: the ID (greater than 0) of the event source.
5448 g_timeout_add_seconds (guint interval,
5449 GSourceFunc function,
5452 g_return_val_if_fail (function != NULL, 0);
5454 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
5458 * g_timeout_add_seconds_once:
5459 * @interval: the time after which the function will be called, in seconds
5460 * @function: function to call
5461 * @data: data to pass to @function
5463 * This function behaves like g_timeout_add_once() but with a range in seconds.
5465 * Returns: the ID (greater than 0) of the event source
5470 g_timeout_add_seconds_once (guint interval,
5471 GSourceOnceFunc function,
5474 return timeout_add_full (G_PRIORITY_DEFAULT, interval, TRUE, TRUE, (GSourceFunc) function, data, NULL);
5477 /* Child watch functions */
5481 siginfo_t_to_wait_status (const siginfo_t *info)
5483 /* Each of these returns is essentially the inverse of WIFEXITED(),
5484 * WIFSIGNALED(), etc. */
5485 switch (info->si_code)
5488 return W_EXITCODE (info->si_status, 0);
5490 return W_EXITCODE (0, info->si_status);
5492 return W_EXITCODE (0, info->si_status | WCOREFLAG);
5494 return __W_CONTINUED;
5498 return W_STOPCODE (info->si_status);
5501 #endif /* HAVE_PIDFD */
5504 g_child_watch_prepare (GSource *source,
5509 #else /* G_OS_WIN32 */
5511 GChildWatchSource *child_watch_source;
5513 child_watch_source = (GChildWatchSource *) source;
5515 if (child_watch_source->poll.fd >= 0)
5518 return g_atomic_int_get (&child_watch_source->child_maybe_exited);
5520 #endif /* G_OS_WIN32 */
5524 g_child_watch_check (GSource *source)
5526 GChildWatchSource *child_watch_source;
5527 gboolean child_exited;
5529 child_watch_source = (GChildWatchSource *) source;
5532 child_exited = !!(child_watch_source->poll.revents & G_IO_IN);
5533 #else /* G_OS_WIN32 */
5535 if (child_watch_source->poll.fd >= 0)
5537 child_exited = !!(child_watch_source->poll.revents & G_IO_IN);
5538 return child_exited;
5540 #endif /* HAVE_PIDFD */
5541 child_exited = g_atomic_int_get (&child_watch_source->child_maybe_exited);
5542 #endif /* G_OS_WIN32 */
5544 return child_exited;
5548 g_child_watch_finalize (GSource *source)
5551 GChildWatchSource *child_watch_source = (GChildWatchSource *) source;
5553 if (child_watch_source->poll.fd >= 0)
5555 close (child_watch_source->poll.fd);
5559 G_LOCK (unix_signal_lock);
5560 unix_child_watches = g_slist_remove (unix_child_watches, source);
5561 unref_unix_signal_handler_unlocked (SIGCHLD);
5562 G_UNLOCK (unix_signal_lock);
5563 #endif /* G_OS_WIN32 */
5569 wake_source (GSource *source)
5571 GMainContext *context;
5573 /* This should be thread-safe:
5575 * - if the source is currently being added to a context, that
5576 * context will be woken up anyway
5578 * - if the source is currently being destroyed, we simply need not
5581 * - the memory for the source will remain valid until after the
5582 * source finalize function was called (which would remove the
5583 * source from the global list which we are currently holding the
5586 * - the GMainContext will either be NULL or point to a live
5589 * - the GMainContext will remain valid since we hold the
5590 * main_context_list lock
5592 * Since we are holding a lot of locks here, don't try to enter any
5593 * more GMainContext functions for fear of dealock -- just hit the
5594 * GWakeup and run. Even if that's safe now, it could easily become
5595 * unsafe with some very minor changes in the future, and signal
5596 * handling is not the most well-tested codepath.
5598 G_LOCK(main_context_list);
5599 context = source->context;
5601 g_wakeup_signal (context->wakeup);
5602 G_UNLOCK(main_context_list);
5606 dispatch_unix_signals_unlocked (void)
5608 gboolean pending[NSIG];
5612 /* clear this first in case another one arrives while we're processing */
5613 g_atomic_int_set (&any_unix_signal_pending, 0);
5615 /* We atomically test/clear the bit from the global array in case
5616 * other signals arrive while we are dispatching.
5618 * We then can safely use our own array below without worrying about
5621 for (i = 0; i < NSIG; i++)
5623 /* Be very careful with (the volatile) unix_signal_pending.
5625 * We must ensure that it's not possible that we clear it without
5626 * handling the signal. We therefore must ensure that our pending
5627 * array has a field set (ie: we will do something about the
5628 * signal) before we clear the item in unix_signal_pending.
5630 * Note specifically: we must check _our_ array.
5632 pending[i] = g_atomic_int_compare_and_exchange (&unix_signal_pending[i], 1, 0);
5635 /* handle GChildWatchSource instances */
5636 if (pending[SIGCHLD])
5638 /* The only way we can do this is to scan all of the children.
5640 * The docs promise that we will not reap children that we are not
5641 * explicitly watching, so that ties our hands from calling
5642 * waitpid(-1). We also can't use siginfo's si_pid field since if
5643 * multiple SIGCHLD arrive at the same time, one of them can be
5644 * dropped (since a given UNIX signal can only be pending once).
5646 for (node = unix_child_watches; node; node = node->next)
5648 GChildWatchSource *source = node->data;
5650 if (g_atomic_int_compare_and_exchange (&source->child_maybe_exited, FALSE, TRUE))
5651 wake_source ((GSource *) source);
5655 /* handle GUnixSignalWatchSource instances */
5656 for (node = unix_signal_watches; node; node = node->next)
5658 GUnixSignalWatchSource *source = node->data;
5660 if (pending[source->signum] &&
5661 g_atomic_int_compare_and_exchange (&source->pending, FALSE, TRUE))
5663 wake_source ((GSource *) source);
5670 dispatch_unix_signals (void)
5672 G_LOCK(unix_signal_lock);
5673 dispatch_unix_signals_unlocked ();
5674 G_UNLOCK(unix_signal_lock);
5678 g_unix_signal_watch_prepare (GSource *source,
5681 GUnixSignalWatchSource *unix_signal_source;
5683 unix_signal_source = (GUnixSignalWatchSource *) source;
5685 return g_atomic_int_get (&unix_signal_source->pending);
5689 g_unix_signal_watch_check (GSource *source)
5691 GUnixSignalWatchSource *unix_signal_source;
5693 unix_signal_source = (GUnixSignalWatchSource *) source;
5695 return g_atomic_int_get (&unix_signal_source->pending);
5699 g_unix_signal_watch_dispatch (GSource *source,
5700 GSourceFunc callback,
5703 GUnixSignalWatchSource *unix_signal_source;
5706 unix_signal_source = (GUnixSignalWatchSource *) source;
5710 g_warning ("Unix signal source dispatched without callback. "
5711 "You must call g_source_set_callback().");
5715 g_atomic_int_set (&unix_signal_source->pending, FALSE);
5717 again = (callback) (user_data);
5723 ref_unix_signal_handler_unlocked (int signum)
5725 /* Ensure we have the worker context */
5726 g_get_worker_context ();
5727 unix_signal_refcount[signum]++;
5728 if (unix_signal_refcount[signum] == 1)
5730 struct sigaction action;
5731 action.sa_handler = g_unix_signal_handler;
5732 sigemptyset (&action.sa_mask);
5734 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
5736 action.sa_flags = SA_NOCLDSTOP;
5738 sigaction (signum, &action, NULL);
5743 unref_unix_signal_handler_unlocked (int signum)
5745 unix_signal_refcount[signum]--;
5746 if (unix_signal_refcount[signum] == 0)
5748 struct sigaction action;
5749 memset (&action, 0, sizeof (action));
5750 action.sa_handler = SIG_DFL;
5751 sigemptyset (&action.sa_mask);
5752 sigaction (signum, &action, NULL);
5756 /* Return a const string to avoid allocations. We lose precision in the case the
5757 * @signum is unrecognised, but that’ll do. */
5758 static const gchar *
5759 signum_to_string (int signum)
5761 /* See `man 0P signal.h` */
5764 return ("GUnixSignalSource: " #s);
5767 /* These signals are guaranteed to exist by POSIX. */
5774 /* Frustratingly, these are not, and hence for brevity the list is
5813 return "GUnixSignalSource: Unrecognized signal";
5819 _g_main_create_unix_signal_watch (int signum)
5822 GUnixSignalWatchSource *unix_signal_source;
5824 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
5825 unix_signal_source = (GUnixSignalWatchSource *) source;
5827 unix_signal_source->signum = signum;
5828 unix_signal_source->pending = FALSE;
5830 /* Set a default name on the source, just in case the caller does not. */
5831 g_source_set_static_name (source, signum_to_string (signum));
5833 G_LOCK (unix_signal_lock);
5834 ref_unix_signal_handler_unlocked (signum);
5835 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5836 dispatch_unix_signals_unlocked ();
5837 G_UNLOCK (unix_signal_lock);
5843 g_unix_signal_watch_finalize (GSource *source)
5845 GUnixSignalWatchSource *unix_signal_source;
5847 unix_signal_source = (GUnixSignalWatchSource *) source;
5849 G_LOCK (unix_signal_lock);
5850 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5851 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5852 G_UNLOCK (unix_signal_lock);
5855 #endif /* G_OS_WIN32 */
5858 g_child_watch_dispatch (GSource *source,
5859 GSourceFunc callback,
5862 GChildWatchSource *child_watch_source;
5863 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5866 child_watch_source = (GChildWatchSource *) source;
5868 /* We only (try to) reap the child process right before dispatching the callback.
5869 * That way, the caller can rely that the process is there until the callback
5870 * is invoked; or, if the caller calls g_source_destroy() without the callback
5871 * being dispatched, the process is still not reaped. */
5878 * Note: We do _not_ check for the special value of STILL_ACTIVE
5879 * since we know that the process has exited and doing so runs into
5880 * problems if the child process "happens to return STILL_ACTIVE(259)"
5881 * as Microsoft's Platform SDK puts it.
5883 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
5885 gchar *emsg = g_win32_error_message (GetLastError ());
5886 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
5889 /* Unknown error. We got signaled that the process might be exited,
5890 * but now we failed to reap it? Assume the process is gone and proceed. */
5894 wait_status = child_status;
5896 #else /* G_OS_WIN32 */
5898 gboolean child_exited = FALSE;
5903 if (child_watch_source->poll.fd >= 0)
5905 siginfo_t child_info = {
5909 /* Get the exit status */
5910 if (waitid (P_PIDFD, child_watch_source->poll.fd, &child_info, WEXITED | WNOHANG) >= 0)
5912 if (child_info.si_pid != 0)
5914 /* waitid() helpfully provides the wait status in a decomposed
5915 * form which is quite useful. Unfortunately we have to report it
5916 * to the #GChildWatchFunc as a waitpid()-style platform-specific
5917 * wait status, so that the user code in #GChildWatchFunc can then
5918 * call WIFEXITED() (etc.) on it. That means re-composing the
5919 * status information. */
5920 wait_status = siginfo_t_to_wait_status (&child_info);
5921 child_exited = TRUE;
5925 g_debug (G_STRLOC ": pidfd signaled but pid %" G_PID_FORMAT " didn't exit",
5926 child_watch_source->pid);
5934 g_warning (G_STRLOC ": waitid(pid:%" G_PID_FORMAT ", pidfd=%d) failed: %s (%d). %s",
5935 child_watch_source->pid, child_watch_source->poll.fd, g_strerror (errsv), errsv,
5936 "See documentation of g_child_watch_source_new() for possible causes.");
5938 /* Assume the process is gone and proceed. */
5939 child_exited = TRUE;
5942 #endif /* HAVE_PIDFD*/
5951 /* We must reset the flag before waitpid(). Otherwise, there would be a
5953 g_atomic_int_set (&child_watch_source->child_maybe_exited, FALSE);
5955 pid = waitpid (child_watch_source->pid, &wstatus, WNOHANG);
5957 if (G_UNLIKELY (pid < 0 && errno == EINTR))
5962 /* Not exited yet. Wait longer. */
5967 wait_status = wstatus;
5972 g_warning (G_STRLOC ": waitpid(pid:%" G_PID_FORMAT ") failed: %s (%d). %s",
5973 child_watch_source->pid, g_strerror (errsv), errsv,
5974 "See documentation of g_child_watch_source_new() for possible causes.");
5976 /* Assume the process is gone and proceed. */
5980 #endif /* G_OS_WIN32 */
5984 g_warning ("Child watch source dispatched without callback. "
5985 "You must call g_source_set_callback().");
5989 (child_watch_callback) (child_watch_source->pid, wait_status, user_data);
5991 /* We never keep a child watch source around as the child is gone */
5998 g_unix_signal_handler (int signum)
6000 gint saved_errno = errno;
6002 #if defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)
6003 g_atomic_int_set (&unix_signal_pending[signum], 1);
6004 g_atomic_int_set (&any_unix_signal_pending, 1);
6006 #warning "Can't use atomics in g_unix_signal_handler(): Unix signal handling will be racy"
6007 unix_signal_pending[signum] = 1;
6008 any_unix_signal_pending = 1;
6011 g_wakeup_signal (glib_worker_context->wakeup);
6013 errno = saved_errno;
6016 #endif /* !G_OS_WIN32 */
6019 * g_child_watch_source_new:
6020 * @pid: process to watch. On POSIX the positive pid of a child process. On
6021 * Windows a handle for a process (which doesn't have to be a child).
6023 * Creates a new child_watch source.
6025 * The source will not initially be associated with any #GMainContext
6026 * and must be added to one with g_source_attach() before it will be
6029 * Note that child watch sources can only be used in conjunction with
6030 * `g_spawn...` when the %G_SPAWN_DO_NOT_REAP_CHILD flag is used.
6032 * Note that on platforms where #GPid must be explicitly closed
6033 * (see g_spawn_close_pid()) @pid must not be closed while the
6034 * source is still active. Typically, you will want to call
6035 * g_spawn_close_pid() in the callback function for the source.
6037 * On POSIX platforms, the following restrictions apply to this API
6038 * due to limitations in POSIX process interfaces:
6040 * * @pid must be a child of this process
6041 * * @pid must be positive
6042 * * the application must not call `waitpid` with a non-positive
6043 * first argument, for instance in another thread
6044 * * the application must not wait for @pid to exit by any other
6045 * mechanism, including `waitpid(pid, ...)` or a second child-watch
6046 * source for the same @pid
6047 * * the application must not ignore `SIGCHLD`
6048 * * Before 2.78, the application could not send a signal (`kill()`) to the
6049 * watched @pid in a race free manner. Since 2.78, you can do that while the
6050 * associated #GMainContext is acquired.
6051 * * Before 2.78, even after destroying the #GSource, you could not
6052 * be sure that @pid wasn't already reaped. Hence, it was also not
6053 * safe to `kill()` or `waitpid()` on the process ID after the child watch
6054 * source was gone. Destroying the source before it fired made it
6055 * impossible to reliably reap the process.
6057 * If any of those conditions are not met, this and related APIs will
6058 * not work correctly. This can often be diagnosed via a GLib warning
6059 * stating that `ECHILD` was received by `waitpid`.
6061 * Calling `waitpid` for specific processes other than @pid remains a
6062 * valid thing to do.
6064 * Returns: the newly-created child watch source
6069 g_child_watch_source_new (GPid pid)
6072 GChildWatchSource *child_watch_source;
6078 g_return_val_if_fail (pid > 0, NULL);
6081 source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
6082 child_watch_source = (GChildWatchSource *)source;
6084 /* Set a default name on the source, just in case the caller does not. */
6085 g_source_set_static_name (source, "GChildWatchSource");
6087 child_watch_source->pid = pid;
6090 child_watch_source->poll.fd = (gintptr) pid;
6091 child_watch_source->poll.events = G_IO_IN;
6093 g_source_add_poll (source, &child_watch_source->poll);
6094 #else /* !G_OS_WIN32 */
6097 /* Use a pidfd, if possible, to avoid having to install a global SIGCHLD
6098 * handler and potentially competing with any other library/code which wants
6101 * Unfortunately this use of pidfd isn’t race-free (the PID could be recycled
6102 * between the caller calling g_child_watch_source_new() and here), but it’s
6103 * better than SIGCHLD.
6105 child_watch_source->poll.fd = (int) syscall (SYS_pidfd_open, pid, 0);
6107 if (child_watch_source->poll.fd >= 0)
6109 child_watch_source->poll.events = G_IO_IN;
6110 g_source_add_poll (source, &child_watch_source->poll);
6115 g_debug ("pidfd_open(%" G_PID_FORMAT ") failed with error: %s",
6116 pid, g_strerror (errsv));
6117 /* Fall through; likely the kernel isn’t new enough to support pidfd_open() */
6118 #endif /* HAVE_PIDFD */
6120 /* We can do that without atomic, as the source is not yet added in
6121 * unix_child_watches (which we do next under a lock). */
6122 child_watch_source->child_maybe_exited = TRUE;
6123 child_watch_source->poll.fd = -1;
6125 G_LOCK (unix_signal_lock);
6126 ref_unix_signal_handler_unlocked (SIGCHLD);
6127 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
6128 G_UNLOCK (unix_signal_lock);
6129 #endif /* !G_OS_WIN32 */
6135 * g_child_watch_add_full: (rename-to g_child_watch_add)
6136 * @priority: the priority of the idle source. Typically this will be in the
6137 * range between %G_PRIORITY_DEFAULT_IDLE and %G_PRIORITY_HIGH_IDLE.
6138 * @pid: process to watch. On POSIX the positive pid of a child process. On
6139 * Windows a handle for a process (which doesn't have to be a child).
6140 * @function: function to call
6141 * @data: data to pass to @function
6142 * @notify: (nullable): function to call when the idle is removed, or %NULL
6144 * Sets a function to be called when the child indicated by @pid
6145 * exits, at the priority @priority.
6147 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
6148 * you will need to pass %G_SPAWN_DO_NOT_REAP_CHILD as flag to
6149 * the spawn function for the child watching to work.
6151 * In many programs, you will want to call g_spawn_check_wait_status()
6152 * in the callback to determine whether or not the child exited
6155 * Also, note that on platforms where #GPid must be explicitly closed
6156 * (see g_spawn_close_pid()) @pid must not be closed while the source
6157 * is still active. Typically, you should invoke g_spawn_close_pid()
6158 * in the callback function for the source.
6160 * GLib supports only a single callback per process id.
6161 * On POSIX platforms, the same restrictions mentioned for
6162 * g_child_watch_source_new() apply to this function.
6164 * This internally creates a main loop source using
6165 * g_child_watch_source_new() and attaches it to the main loop context
6166 * using g_source_attach(). You can do these steps manually if you
6167 * need greater control.
6169 * Returns: the ID (greater than 0) of the event source.
6174 g_child_watch_add_full (gint priority,
6176 GChildWatchFunc function,
6178 GDestroyNotify notify)
6183 g_return_val_if_fail (function != NULL, 0);
6185 g_return_val_if_fail (pid > 0, 0);
6188 source = g_child_watch_source_new (pid);
6190 if (priority != G_PRIORITY_DEFAULT)
6191 g_source_set_priority (source, priority);
6193 g_source_set_callback (source, (GSourceFunc) function, data, notify);
6194 id = g_source_attach (source, NULL);
6195 g_source_unref (source);
6201 * g_child_watch_add:
6202 * @pid: process id to watch. On POSIX the positive pid of a child
6203 * process. On Windows a handle for a process (which doesn't have
6205 * @function: function to call
6206 * @data: data to pass to @function
6208 * Sets a function to be called when the child indicated by @pid
6209 * exits, at a default priority, %G_PRIORITY_DEFAULT.
6211 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
6212 * you will need to pass %G_SPAWN_DO_NOT_REAP_CHILD as flag to
6213 * the spawn function for the child watching to work.
6215 * Note that on platforms where #GPid must be explicitly closed
6216 * (see g_spawn_close_pid()) @pid must not be closed while the
6217 * source is still active. Typically, you will want to call
6218 * g_spawn_close_pid() in the callback function for the source.
6220 * GLib supports only a single callback per process id.
6221 * On POSIX platforms, the same restrictions mentioned for
6222 * g_child_watch_source_new() apply to this function.
6224 * This internally creates a main loop source using
6225 * g_child_watch_source_new() and attaches it to the main loop context
6226 * using g_source_attach(). You can do these steps manually if you
6227 * need greater control.
6229 * Returns: the ID (greater than 0) of the event source.
6234 g_child_watch_add (GPid pid,
6235 GChildWatchFunc function,
6238 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
6242 /* Idle functions */
6245 g_idle_prepare (GSource *source,
6254 g_idle_check (GSource *source)
6260 g_idle_dispatch (GSource *source,
6261 GSourceFunc callback,
6264 GIdleSource *idle_source = (GIdleSource *)source;
6269 g_warning ("Idle source dispatched without callback. "
6270 "You must call g_source_set_callback().");
6274 if (idle_source->one_shot)
6276 GSourceOnceFunc once_callback = (GSourceOnceFunc) callback;
6277 once_callback (user_data);
6278 again = G_SOURCE_REMOVE;
6282 again = callback (user_data);
6285 TRACE (GLIB_IDLE_DISPATCH (source, source->context, callback, user_data, again));
6291 idle_source_new (gboolean one_shot)
6294 GIdleSource *idle_source;
6296 source = g_source_new (&g_idle_funcs, sizeof (GIdleSource));
6297 idle_source = (GIdleSource *) source;
6299 idle_source->one_shot = one_shot;
6301 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
6303 /* Set a default name on the source, just in case the caller does not. */
6304 g_source_set_static_name (source, "GIdleSource");
6310 * g_idle_source_new:
6312 * Creates a new idle source.
6314 * The source will not initially be associated with any #GMainContext
6315 * and must be added to one with g_source_attach() before it will be
6316 * executed. Note that the default priority for idle sources is
6317 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
6318 * have a default priority of %G_PRIORITY_DEFAULT.
6320 * Returns: the newly-created idle source
6323 g_idle_source_new (void)
6325 return idle_source_new (FALSE);
6329 idle_add_full (gint priority,
6331 GSourceFunc function,
6333 GDestroyNotify notify)
6338 g_return_val_if_fail (function != NULL, 0);
6340 source = idle_source_new (one_shot);
6342 if (priority != G_PRIORITY_DEFAULT_IDLE)
6343 g_source_set_priority (source, priority);
6345 g_source_set_callback (source, function, data, notify);
6346 id = g_source_attach (source, NULL);
6348 TRACE (GLIB_IDLE_ADD (source, g_main_context_default (), id, priority, function, data));
6350 g_source_unref (source);
6356 * g_idle_add_full: (rename-to g_idle_add)
6357 * @priority: the priority of the idle source. Typically this will be in the
6358 * range between %G_PRIORITY_DEFAULT_IDLE and %G_PRIORITY_HIGH_IDLE.
6359 * @function: function to call
6360 * @data: data to pass to @function
6361 * @notify: (nullable): function to call when the idle is removed, or %NULL
6363 * Adds a function to be called whenever there are no higher priority
6366 * If the function returns %G_SOURCE_REMOVE or %FALSE it is automatically
6367 * removed from the list of event sources and will not be called again.
6369 * See [memory management of sources][mainloop-memory-management] for details
6370 * on how to handle the return value and memory management of @data.
6372 * This internally creates a main loop source using g_idle_source_new()
6373 * and attaches it to the global #GMainContext using g_source_attach(), so
6374 * the callback will be invoked in whichever thread is running that main
6375 * context. You can do these steps manually if you need greater control or to
6376 * use a custom main context.
6378 * Returns: the ID (greater than 0) of the event source.
6381 g_idle_add_full (gint priority,
6382 GSourceFunc function,
6384 GDestroyNotify notify)
6386 return idle_add_full (priority, FALSE, function, data, notify);
6391 * @function: function to call
6392 * @data: data to pass to @function.
6394 * Adds a function to be called whenever there are no higher priority
6395 * events pending to the default main loop. The function is given the
6396 * default idle priority, %G_PRIORITY_DEFAULT_IDLE. If the function
6397 * returns %FALSE it is automatically removed from the list of event
6398 * sources and will not be called again.
6400 * See [memory management of sources][mainloop-memory-management] for details
6401 * on how to handle the return value and memory management of @data.
6403 * This internally creates a main loop source using g_idle_source_new()
6404 * and attaches it to the global #GMainContext using g_source_attach(), so
6405 * the callback will be invoked in whichever thread is running that main
6406 * context. You can do these steps manually if you need greater control or to
6407 * use a custom main context.
6409 * Returns: the ID (greater than 0) of the event source.
6412 g_idle_add (GSourceFunc function,
6415 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
6420 * @function: function to call
6421 * @data: data to pass to @function
6423 * Adds a function to be called whenever there are no higher priority
6424 * events pending to the default main loop. The function is given the
6425 * default idle priority, %G_PRIORITY_DEFAULT_IDLE.
6427 * The function will only be called once and then the source will be
6428 * automatically removed from the main context.
6430 * This function otherwise behaves like g_idle_add().
6432 * Returns: the ID (greater than 0) of the event source
6437 g_idle_add_once (GSourceOnceFunc function,
6440 return idle_add_full (G_PRIORITY_DEFAULT_IDLE, TRUE, (GSourceFunc) function, data, NULL);
6444 * g_idle_remove_by_data:
6445 * @data: the data for the idle source's callback.
6447 * Removes the idle function with the given data.
6449 * Returns: %TRUE if an idle source was found and removed.
6452 g_idle_remove_by_data (gpointer data)
6454 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
6458 * g_main_context_invoke:
6459 * @context: (nullable): a #GMainContext, or %NULL for the global-default
6461 * @function: function to call
6462 * @data: data to pass to @function
6464 * Invokes a function in such a way that @context is owned during the
6465 * invocation of @function.
6467 * If @context is %NULL then the global-default main context — as
6468 * returned by g_main_context_default() — is used.
6470 * If @context is owned by the current thread, @function is called
6471 * directly. Otherwise, if @context is the thread-default main context
6472 * of the current thread and g_main_context_acquire() succeeds, then
6473 * @function is called and g_main_context_release() is called
6476 * In any other case, an idle source is created to call @function and
6477 * that source is attached to @context (presumably to be run in another
6478 * thread). The idle source is attached with %G_PRIORITY_DEFAULT
6479 * priority. If you want a different priority, use
6480 * g_main_context_invoke_full().
6482 * Note that, as with normal idle functions, @function should probably
6483 * return %FALSE. If it returns %TRUE, it will be continuously run in a
6484 * loop (and may prevent this call from returning).
6489 g_main_context_invoke (GMainContext *context,
6490 GSourceFunc function,
6493 g_main_context_invoke_full (context,
6495 function, data, NULL);
6499 * g_main_context_invoke_full:
6500 * @context: (nullable): a #GMainContext, or %NULL for the global-default
6502 * @priority: the priority at which to run @function
6503 * @function: function to call
6504 * @data: data to pass to @function
6505 * @notify: (nullable): a function to call when @data is no longer in use, or %NULL.
6507 * Invokes a function in such a way that @context is owned during the
6508 * invocation of @function.
6510 * This function is the same as g_main_context_invoke() except that it
6511 * lets you specify the priority in case @function ends up being
6512 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
6514 * @notify should not assume that it is called from any particular
6515 * thread or with any particular context acquired.
6520 g_main_context_invoke_full (GMainContext *context,
6522 GSourceFunc function,
6524 GDestroyNotify notify)
6526 g_return_if_fail (function != NULL);
6529 context = g_main_context_default ();
6531 if (g_main_context_is_owner (context))
6533 while (function (data));
6540 GMainContext *thread_default;
6542 thread_default = g_main_context_get_thread_default ();
6544 if (!thread_default)
6545 thread_default = g_main_context_default ();
6547 if (thread_default == context && g_main_context_acquire (context))
6549 while (function (data));
6551 g_main_context_release (context);
6560 source = g_idle_source_new ();
6561 g_source_set_priority (source, priority);
6562 g_source_set_callback (source, function, data, notify);
6563 g_source_attach (source, context);
6564 g_source_unref (source);
6570 glib_worker_main (gpointer data)
6574 g_main_context_iteration (glib_worker_context, TRUE);
6577 if (g_atomic_int_get (&any_unix_signal_pending))
6578 dispatch_unix_signals ();
6582 return NULL; /* worst GCC warning message ever... */
6586 g_get_worker_context (void)
6588 static gsize initialised;
6590 if (g_once_init_enter (&initialised))
6592 /* mask all signals in the worker thread */
6598 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
6600 glib_worker_context = g_main_context_new ();
6601 g_thread_new ("gmain", glib_worker_main, NULL);
6603 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
6605 g_once_init_leave (&initialised, TRUE);
6608 return glib_worker_context;
6613 * @fd_ptr: (not optional) (inout): A pointer to a file descriptor
6615 * Sets @fd_ptr to `-1`, returning the value that was there before.
6617 * Conceptually, this transfers the ownership of the file descriptor
6618 * from the referenced variable to the caller of the function (i.e.
6619 * ‘steals’ the reference). This is very similar to g_steal_pointer(),
6620 * but for file descriptors.
6622 * On POSIX platforms, this function is async-signal safe
6623 * (see [`signal(7)`](man:signal(7)) and
6624 * [`signal-safety(7)`](man:signal-safety(7))), making it safe to call from a
6625 * signal handler or a #GSpawnChildSetupFunc.
6627 * This function preserves the value of `errno`.
6629 * Returns: the value that @fd_ptr previously had