1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gpoll.c: poll(2) abstraction
5 * Copyright 1998 Owen Taylor
6 * Copyright 2008 Red Hat, Inc.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
24 * file for a list of people on the GLib Team. See the ChangeLog
25 * files for a list of changes. These files are distributed with
26 * GLib at ftp://ftp.gtk.org/pub/gtk/.
34 #include "glibconfig.h"
35 #include "giochannel.h"
37 /* Uncomment the next line (and the corresponding line in gmain.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
50 #include <sys/types.h>
53 #ifdef HAVE_SYS_TIME_H
55 #endif /* HAVE_SYS_TIME_H */
59 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
60 * so we prefer our own poll emulation.
62 #if defined(_POLL_EMUL_H_) || defined(BROKEN_POLL)
66 #endif /* GLIB_HAVE_SYS_POLL_H */
69 #endif /* G_OS_UNIX */
76 #endif /* G_OS_WIN32 */
84 #ifdef G_MAIN_POLL_DEBUG
85 extern gboolean _g_main_poll_debug;
92 * @fds: file descriptors to poll
93 * @nfds: the number of file descriptors in @fds
94 * @timeout: amount of time to wait, in milliseconds, or -1 to wait forever
96 * Polls @fds, as with the poll() system call, but portably. (On
97 * systems that don't have poll(), it is emulated using select().)
98 * This is used internally by #GMainContext, but it can be called
99 * directly if you need to block until a file descriptor is ready, but
100 * don't want to run the full main loop.
102 * Each element of @fds is a #GPollFD describing a single file
103 * descriptor to poll. The @fd field indicates the file descriptor,
104 * and the @events field indicates the events to poll for. On return,
105 * the @revents fields will be filled with the events that actually
108 * On POSIX systems, the file descriptors in @fds can be any sort of
109 * file descriptor, but the situation is much more complicated on
110 * Windows. If you need to use g_poll() in code that has to run on
111 * Windows, the easiest solution is to construct all of your
112 * #GPollFDs with g_io_channel_win32_make_pollfd().
114 * Returns: the number of entries in @fds whose @revents fields
115 * were filled in, or 0 if the operation timed out, or -1 on error or
116 * if the call was interrupted.
121 g_poll (GPollFD *fds,
125 return poll ((struct pollfd *)fds, nfds, timeout);
128 #else /* !HAVE_POLL */
133 poll_rest (GPollFD *msg_fd,
136 GPollFD *handle_to_fd[],
146 /* Wait for either messages or handles
147 * -> Use MsgWaitForMultipleObjectsEx
149 if (_g_main_poll_debug)
150 g_print (" MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout_ms);
152 ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout_ms,
153 QS_ALLINPUT, MWMO_ALERTABLE);
155 if (ready == WAIT_FAILED)
157 gchar *emsg = g_win32_error_message (GetLastError ());
158 g_warning ("MsgWaitForMultipleObjectsEx failed: %s", emsg);
162 else if (nhandles == 0)
164 /* No handles to wait for, just the timeout */
165 if (timeout_ms == INFINITE)
169 /* Wait for the current process to die, more efficient than SleepEx(). */
170 WaitForSingleObjectEx (GetCurrentProcess (), timeout_ms, TRUE);
171 ready = WAIT_TIMEOUT;
176 /* Wait for just handles
177 * -> Use WaitForMultipleObjectsEx
179 if (_g_main_poll_debug)
180 g_print (" WaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout_ms);
182 ready = WaitForMultipleObjectsEx (nhandles, handles, FALSE, timeout_ms, TRUE);
183 if (ready == WAIT_FAILED)
185 gchar *emsg = g_win32_error_message (GetLastError ());
186 g_warning ("WaitForMultipleObjectsEx failed: %s", emsg);
191 if (_g_main_poll_debug)
192 g_print (" wait returns %ld%s\n",
194 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
195 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
196 (msg_fd != NULL && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
198 if (ready == WAIT_FAILED)
200 else if (ready == WAIT_TIMEOUT ||
201 ready == WAIT_IO_COMPLETION)
203 else if (msg_fd != NULL && ready == WAIT_OBJECT_0 + nhandles)
205 msg_fd->revents |= G_IO_IN;
207 /* If we have a timeout, or no handles to poll, be satisfied
208 * with just noticing we have messages waiting.
210 if (timeout_ms != 0 || nhandles == 0)
213 /* If no timeout and handles to poll, recurse to poll them,
216 recursed_result = poll_rest (NULL, stop_fd, handles, handle_to_fd, nhandles, 0);
217 return (recursed_result == -1) ? -1 : 1 + recursed_result;
219 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
223 f = handle_to_fd[ready - WAIT_OBJECT_0];
224 f->revents = f->events;
225 if (_g_main_poll_debug)
226 g_print (" got event %p\n", (HANDLE) f->fd);
228 /* Do not count the stop_fd */
229 retval = (f != stop_fd) ? 1 : 0;
231 /* If no timeout and polling several handles, recurse to poll
234 if (timeout_ms == 0 && nhandles > 1)
236 /* Poll the handles with index > ready */
237 HANDLE *shorter_handles;
238 GPollFD **shorter_handle_to_fd;
239 gint shorter_nhandles;
241 shorter_handles = &handles[ready - WAIT_OBJECT_0 + 1];
242 shorter_handle_to_fd = &handle_to_fd[ready - WAIT_OBJECT_0 + 1];
243 shorter_nhandles = nhandles - (ready - WAIT_OBJECT_0 + 1);
245 recursed_result = poll_rest (NULL, stop_fd, shorter_handles, shorter_handle_to_fd, shorter_nhandles, 0);
246 return (recursed_result == -1) ? -1 : retval + recursed_result;
256 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
257 GPollFD *handle_to_fd[MAXIMUM_WAIT_OBJECTS];
262 } GWin32PollThreadData;
265 poll_single_thread (GWin32PollThreadData *data)
269 /* Polling for several things? */
270 if (data->nhandles > 1 || (data->nhandles > 0 && data->msg_fd != NULL))
272 /* First check if one or several of them are immediately
275 retval = poll_rest (data->msg_fd, data->stop_fd, data->handles, data->handle_to_fd, data->nhandles, 0);
277 /* If not, and we have a significant timeout, poll again with
278 * timeout then. Note that this will return indication for only
279 * one event, or only for messages.
281 if (retval == 0 && (data->timeout_ms == INFINITE || data->timeout_ms > 0))
282 retval = poll_rest (data->msg_fd, data->stop_fd, data->handles, data->handle_to_fd, data->nhandles, data->timeout_ms);
286 /* Just polling for one thing, so no need to check first if
287 * available immediately
289 retval = poll_rest (data->msg_fd, data->stop_fd, data->handles, data->handle_to_fd, data->nhandles, data->timeout_ms);
296 fill_poll_thread_data (GPollFD *fds,
300 GWin32PollThreadData *data)
304 data->timeout_ms = timeout_ms;
308 if (_g_main_poll_debug)
309 g_print (" Stop FD: %p", (HANDLE) stop_fd->fd);
311 g_assert (data->nhandles < MAXIMUM_WAIT_OBJECTS);
313 data->stop_fd = stop_fd;
314 data->handle_to_fd[data->nhandles] = stop_fd;
315 data->handles[data->nhandles++] = (HANDLE) stop_fd->fd;
318 for (f = fds; f < &fds[nfds]; ++f)
320 if ((data->nhandles == MAXIMUM_WAIT_OBJECTS) ||
321 (data->msg_fd != NULL && (data->nhandles == MAXIMUM_WAIT_OBJECTS - 1)))
323 g_warning ("Too many handles to wait for!");
327 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
329 if (_g_main_poll_debug && data->msg_fd == NULL)
335 if (_g_main_poll_debug)
336 g_print (" %p", (HANDLE) f->fd);
337 data->handle_to_fd[data->nhandles] = f;
338 data->handles[data->nhandles++] = (HANDLE) f->fd;
345 static guint __stdcall
346 poll_thread_run (gpointer user_data)
348 GWin32PollThreadData *data = user_data;
350 /* Docs say that it is safer to call _endthreadex by our own:
351 * https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/endthread-endthreadex
353 _endthreadex (poll_single_thread (data));
355 g_assert_not_reached ();
360 /* One slot for a possible msg object or the stop event */
361 #define MAXIMUM_WAIT_OBJECTS_PER_THREAD (MAXIMUM_WAIT_OBJECTS - 1)
364 g_poll (GPollFD *fds,
368 guint nthreads, threads_remain;
369 HANDLE thread_handles[MAXIMUM_WAIT_OBJECTS];
370 GWin32PollThreadData *threads_data;
371 GPollFD stop_event = { 0, };
373 guint i, fds_idx = 0;
377 GPollFD *msg_fd = NULL;
382 /* Simple case without extra threads */
383 if (nfds <= MAXIMUM_WAIT_OBJECTS)
385 GWin32PollThreadData data = { 0, };
387 if (_g_main_poll_debug)
388 g_print ("g_poll: waiting for");
390 fill_poll_thread_data (fds, nfds, timeout, NULL, &data);
392 if (_g_main_poll_debug)
395 retval = poll_single_thread (&data);
397 for (f = fds; f < &fds[nfds]; ++f)
403 if (_g_main_poll_debug)
404 g_print ("g_poll: polling with threads\n");
406 nthreads = nfds / MAXIMUM_WAIT_OBJECTS_PER_THREAD;
407 threads_remain = nfds % MAXIMUM_WAIT_OBJECTS_PER_THREAD;
408 if (threads_remain > 0)
411 if (nthreads > MAXIMUM_WAIT_OBJECTS_PER_THREAD)
413 g_warning ("Too many handles to wait for in threads!");
414 nthreads = MAXIMUM_WAIT_OBJECTS_PER_THREAD;
417 #if GLIB_SIZEOF_VOID_P == 8
418 stop_event.fd = (gint64)CreateEventW (NULL, TRUE, FALSE, NULL);
420 stop_event.fd = (gint)CreateEventW (NULL, TRUE, FALSE, NULL);
422 stop_event.events = G_IO_IN;
424 threads_data = g_new0 (GWin32PollThreadData, nthreads);
425 for (i = 0; i < nthreads; i++)
430 if (i == (nthreads - 1) && threads_remain > 0)
431 thread_fds = threads_remain;
433 thread_fds = MAXIMUM_WAIT_OBJECTS_PER_THREAD;
435 fill_poll_thread_data (fds + fds_idx, thread_fds, timeout, &stop_event, &threads_data[i]);
436 fds_idx += thread_fds;
438 /* We must poll for messages from the same thread, so poll it along with the threads */
439 if (threads_data[i].msg_fd != NULL)
441 msg_fd = threads_data[i].msg_fd;
442 threads_data[i].msg_fd = NULL;
445 thread_handles[i] = (HANDLE) _beginthreadex (NULL, 0, poll_thread_run, &threads_data[i], 0, &ignore);
448 /* Wait for at least one thread to return */
450 ready = MsgWaitForMultipleObjectsEx (nthreads, thread_handles, timeout,
451 QS_ALLINPUT, MWMO_ALERTABLE);
453 ready = WaitForMultipleObjects (nthreads, thread_handles, timeout > 0, timeout);
455 /* Signal the stop in case any of the threads did not stop yet */
456 if (!SetEvent ((HANDLE)stop_event.fd))
458 gchar *emsg = g_win32_error_message (GetLastError ());
459 g_warning ("gpoll: failed to signal the stop event: %s", emsg);
463 /* Wait for the rest of the threads to finish */
464 WaitForMultipleObjects (nthreads, thread_handles, TRUE, INFINITE);
466 /* The return value of all the threads give us all the fds that changed state */
468 if (msg_fd != NULL && ready == WAIT_OBJECT_0 + nthreads)
470 msg_fd->revents |= G_IO_IN;
474 for (i = 0; i < nthreads; i++)
476 if (GetExitCodeThread (thread_handles[i], &thread_retval))
477 retval = retval == -1 ? -1 : thread_retval == -1 ? -1 : retval + thread_retval;
479 CloseHandle (thread_handles[i]);
483 for (f = fds; f < &fds[nfds]; ++f)
486 g_free (threads_data);
487 CloseHandle ((HANDLE)stop_event.fd);
492 #else /* !G_OS_WIN32 */
494 /* The following implementation of poll() comes from the GNU C Library.
495 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
498 #include <string.h> /* for bzero on BSD systems */
500 #ifdef HAVE_SYS_SELECT_H
501 #include <sys/select.h>
502 #endif /* HAVE_SYS_SELECT_H */
505 g_poll (GPollFD *fds,
510 fd_set rset, wset, xset;
519 for (f = fds; f < &fds[nfds]; ++f)
522 if (f->events & G_IO_IN)
523 FD_SET (f->fd, &rset);
524 if (f->events & G_IO_OUT)
525 FD_SET (f->fd, &wset);
526 if (f->events & G_IO_PRI)
527 FD_SET (f->fd, &xset);
528 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
532 tv.tv_sec = timeout / 1000;
533 tv.tv_usec = (timeout % 1000) * 1000;
535 ready = select (maxfd + 1, &rset, &wset, &xset,
536 timeout == -1 ? NULL : &tv);
538 for (f = fds; f < &fds[nfds]; ++f)
543 if (FD_ISSET (f->fd, &rset))
544 f->revents |= G_IO_IN;
545 if (FD_ISSET (f->fd, &wset))
546 f->revents |= G_IO_OUT;
547 if (FD_ISSET (f->fd, &xset))
548 f->revents |= G_IO_PRI;
555 #endif /* !G_OS_WIN32 */
557 #endif /* !HAVE_POLL */