gmessages: Fix up testing commit to handle fatal masquerading
[platform/upstream/glib.git] / glib / glib-unix.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 2011 Red Hat, Inc.
3  *
4  * glib-unix.c: UNIX specific API wrappers and convenience functions
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Authors: Colin Walters <walters@verbum.org>
22  */
23
24 #include "config.h"
25
26 /* To make bionic export pipe2() */
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE 1
29 #endif
30
31 #include "glib-unix.h"
32 #include "gmain-internal.h"
33
34 #include <string.h>
35
36 /**
37  * SECTION:gunix
38  * @title: UNIX-specific utilities and integration
39  * @short_description: pipes, signal handling
40  * @include: glib-unix.h
41  *
42  * Most of GLib is intended to be portable; in contrast, this set of
43  * functions is designed for programs which explicitly target UNIX,
44  * or are using it to build higher level abstractions which would be
45  * conditionally compiled if the platform matches G_OS_UNIX.
46  *
47  * To use these functions, you must explicitly include the
48  * "glib-unix.h" header.
49  */
50
51 G_DEFINE_QUARK (g-unix-error-quark, g_unix_error)
52
53 static gboolean
54 g_unix_set_error_from_errno (GError **error,
55                              gint     saved_errno)
56 {
57   g_set_error_literal (error,
58                        G_UNIX_ERROR,
59                        0,
60                        g_strerror (saved_errno));
61   errno = saved_errno;
62   return FALSE;
63 }
64
65 /**
66  * g_unix_open_pipe:
67  * @fds: Array of two integers
68  * @flags: Bitfield of file descriptor flags, see "man 2 fcntl"
69  * @error: a #GError
70  *
71  * Similar to the UNIX pipe() call, but on modern systems like Linux
72  * uses the pipe2() system call, which atomically creates a pipe with
73  * the configured flags.  The only supported flag currently is
74  * <literal>FD_CLOEXEC</literal>.  If for example you want to configure
75  * <literal>O_NONBLOCK</literal>, that must still be done separately with
76  * fcntl().
77  *
78  * <note>This function does *not* take <literal>O_CLOEXEC</literal>, it takes
79  * <literal>FD_CLOEXEC</literal> as if for fcntl(); these are
80  * different on Linux/glibc.</note>
81  *
82  * Returns: %TRUE on success, %FALSE if not (and errno will be set).
83  *
84  * Since: 2.30
85  */
86 gboolean
87 g_unix_open_pipe (int     *fds,
88                   int      flags,
89                   GError **error)
90 {
91   int ecode;
92
93   /* We only support FD_CLOEXEC */
94   g_return_val_if_fail ((flags & (FD_CLOEXEC)) == flags, FALSE);
95
96 #ifdef HAVE_PIPE2
97   {
98     int pipe2_flags = 0;
99     if (flags & FD_CLOEXEC)
100       pipe2_flags |= O_CLOEXEC;
101     /* Atomic */
102     ecode = pipe2 (fds, pipe2_flags);
103     if (ecode == -1 && errno != ENOSYS)
104       return g_unix_set_error_from_errno (error, errno);
105     else if (ecode == 0)
106       return TRUE;
107     /* Fall through on -ENOSYS, we must be running on an old kernel */
108   }
109 #endif
110   ecode = pipe (fds);
111   if (ecode == -1)
112     return g_unix_set_error_from_errno (error, errno);
113
114   if (flags == 0)
115     return TRUE;
116
117   ecode = fcntl (fds[0], F_SETFD, flags);
118   if (ecode == -1)
119     {
120       int saved_errno = errno;
121       close (fds[0]);
122       close (fds[1]);
123       return g_unix_set_error_from_errno (error, saved_errno);
124     }
125   ecode = fcntl (fds[1], F_SETFD, flags);
126   if (ecode == -1)
127     {
128       int saved_errno = errno;
129       close (fds[0]);
130       close (fds[1]);
131       return g_unix_set_error_from_errno (error, saved_errno);
132     }
133   return TRUE;
134 }
135
136 /**
137  * g_unix_set_fd_nonblocking:
138  * @fd: A file descriptor
139  * @nonblock: If %TRUE, set the descriptor to be non-blocking
140  * @error: a #GError
141  *
142  * Control the non-blocking state of the given file descriptor,
143  * according to @nonblock.  On most systems this uses <literal>O_NONBLOCK</literal>, but
144  * on some older ones may use <literal>O_NDELAY</literal>.
145  *
146  * Returns: %TRUE if successful
147  *
148  * Since: 2.30
149  */
150 gboolean
151 g_unix_set_fd_nonblocking (gint       fd,
152                            gboolean   nonblock,
153                            GError   **error)
154 {
155 #ifdef F_GETFL
156   glong fcntl_flags;
157   fcntl_flags = fcntl (fd, F_GETFL);
158
159   if (fcntl_flags == -1)
160     return g_unix_set_error_from_errno (error, errno);
161
162   if (nonblock)
163     {
164 #ifdef O_NONBLOCK
165       fcntl_flags |= O_NONBLOCK;
166 #else
167       fcntl_flags |= O_NDELAY;
168 #endif
169     }
170   else
171     {
172 #ifdef O_NONBLOCK
173       fcntl_flags &= ~O_NONBLOCK;
174 #else
175       fcntl_flags &= ~O_NDELAY;
176 #endif
177     }
178
179   if (fcntl (fd, F_SETFL, fcntl_flags) == -1)
180     return g_unix_set_error_from_errno (error, errno);
181   return TRUE;
182 #else
183   return g_unix_set_error_from_errno (error, EINVAL);
184 #endif
185 }
186
187 /**
188  * g_unix_signal_source_new:
189  * @signum: A signal number
190  *
191  * Create a #GSource that will be dispatched upon delivery of the UNIX
192  * signal @signum.  In GLib versions before 2.36, only
193  * <literal>SIGHUP</literal>, <literal>SIGINT</literal>,
194  * <literal>SIGTERM</literal> can be monitored.  In GLib 2.36,
195  * <literal>SIGUSR1</literal> and <literal>SIGUSR2</literal> were
196  * added.
197  *
198  * Note that unlike the UNIX default, all sources which have created a
199  * watch will be dispatched, regardless of which underlying thread
200  * invoked g_unix_signal_source_new().
201  *
202  * For example, an effective use of this function is to handle <literal>SIGTERM</literal>
203  * cleanly; flushing any outstanding files, and then calling
204  * g_main_loop_quit ().  It is not safe to do any of this a regular
205  * UNIX signal handler; your handler may be invoked while malloc() or
206  * another library function is running, causing reentrancy if you
207  * attempt to use it from the handler.  None of the GLib/GObject API
208  * is safe against this kind of reentrancy.
209  *
210  * The interaction of this source when combined with native UNIX
211  * functions like sigprocmask() is not defined.
212  *
213  * The source will not initially be associated with any #GMainContext
214  * and must be added to one with g_source_attach() before it will be
215  * executed.
216  *
217  * Returns: A newly created #GSource
218  *
219  * Since: 2.30
220  */
221 GSource *
222 g_unix_signal_source_new (int signum)
223 {
224   g_return_val_if_fail (signum == SIGHUP || signum == SIGINT || signum == SIGTERM ||
225                         signum == SIGUSR1 || signum == SIGUSR2, NULL);
226
227   return _g_main_create_unix_signal_watch (signum);
228 }
229
230 /**
231  * g_unix_signal_add_full:
232  * @priority: the priority of the signal source. Typically this will be in
233  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
234  * @signum: Signal number
235  * @handler: Callback
236  * @user_data: Data for @handler
237  * @notify: #GDestroyNotify for @handler
238  *
239  * A convenience function for g_unix_signal_source_new(), which
240  * attaches to the default #GMainContext.  You can remove the watch
241  * using g_source_remove().
242  *
243  * Returns: An ID (greater than 0) for the event source
244  *
245  * Rename to: g_unix_signal_add
246  * Since: 2.30
247  */
248 guint
249 g_unix_signal_add_full (int            priority,
250                         int            signum,
251                         GSourceFunc    handler,
252                         gpointer       user_data,
253                         GDestroyNotify notify)
254 {
255   guint id;
256   GSource *source;
257
258   source = g_unix_signal_source_new (signum);
259
260   if (priority != G_PRIORITY_DEFAULT)
261     g_source_set_priority (source, priority);
262
263   g_source_set_callback (source, handler, user_data, notify);
264   id = g_source_attach (source, NULL);
265   g_source_unref (source);
266
267   return id;
268 }
269
270 /**
271  * g_unix_signal_add:
272  * @signum: Signal number
273  * @handler: Callback
274  * @user_data: Data for @handler
275  *
276  * A convenience function for g_unix_signal_source_new(), which
277  * attaches to the default #GMainContext.  You can remove the watch
278  * using g_source_remove().
279  *
280  * Returns: An ID (greater than 0) for the event source
281  *
282  * Since: 2.30
283  */
284 guint
285 g_unix_signal_add (int         signum,
286                    GSourceFunc handler,
287                    gpointer    user_data)
288 {
289   return g_unix_signal_add_full (G_PRIORITY_DEFAULT, signum, handler, user_data, NULL);
290 }
291
292 typedef struct
293 {
294   GSource source;
295
296   gint     fd;
297   gpointer tag;
298 } GUnixFDSource;
299
300 static gboolean
301 g_unix_fd_source_dispatch (GSource     *source,
302                            GSourceFunc  callback,
303                            gpointer     user_data)
304 {
305   GUnixFDSource *fd_source = (GUnixFDSource *) source;
306   GUnixFDSourceFunc func = (GUnixFDSourceFunc) callback;
307
308   if (!callback)
309     {
310       g_warning ("GUnixFDSource dispatched without callback\n"
311                  "You must call g_source_set_callback().");
312       return FALSE;
313     }
314
315   return (* func) (fd_source->fd, g_source_query_unix_fd (source, fd_source->tag), user_data);
316 }
317
318
319 /**
320  * g_unix_fd_source_new:
321  * @fd: a file descriptor
322  * @condition: IO conditions to watch for on @fd
323  *
324  * Creates a #GSource to watch for a particular IO condition on a file
325  * descriptor.
326  *
327  * The source will never close the fd -- you must do it yourself.
328  *
329  * Returns: the newly created #GSource
330  *
331  * Since: 2.36
332  **/
333 GSource *
334 g_unix_fd_source_new (gint         fd,
335                       GIOCondition condition)
336 {
337   static GSourceFuncs source_funcs = {
338     NULL, NULL, g_unix_fd_source_dispatch, NULL
339   };
340   GUnixFDSource *fd_source;
341   GSource *source;
342
343   source = g_source_new (&source_funcs, sizeof (GUnixFDSource));
344   fd_source = (GUnixFDSource *) source;
345
346   fd_source->fd = fd;
347   fd_source->tag = g_source_add_unix_fd (source, fd, condition);
348
349   return source;
350 }
351
352 /**
353  * g_unix_fd_add_full:
354  * @priority: the priority of the source
355  * @fd: a file descriptor
356  * @condition: IO conditions to watch for on @fd
357  * @function: a #GUnixFDSourceFunc
358  * @user_data: data to pass to @function
359  * @notify: function to call when the idle is removed, or %NULL
360  *
361  * Sets a function to be called when the IO condition, as specified by
362  * @condition becomes true for @fd.
363  *
364  * This is the same as g_unix_fd_add(), except that it allows you to
365  * specify a non-default priority and a provide a #GDestroyNotify for
366  * @user_data.
367  *
368  * Returns: the ID (greater than 0) of the event source
369  *
370  * Since: 2.36
371  **/
372 guint
373 g_unix_fd_add_full (gint              priority,
374                     gint              fd,
375                     GIOCondition      condition,
376                     GUnixFDSourceFunc function,
377                     gpointer          user_data,
378                     GDestroyNotify    notify)
379 {
380   GSource *source;
381   guint id;
382
383   g_return_val_if_fail (function != NULL, 0);
384
385   source = g_unix_fd_source_new (fd, condition);
386
387   if (priority != G_PRIORITY_DEFAULT)
388     g_source_set_priority (source, priority);
389
390   g_source_set_callback (source, (GSourceFunc) function, user_data, notify);
391   id = g_source_attach (source, NULL);
392   g_source_unref (source);
393
394   return id;
395 }
396
397 /**
398  * g_unix_fd_add:
399  * @fd: a file descriptor
400  * @condition: IO conditions to watch for on @fd
401  * @function: a #GPollFDFunc
402  * @user_data: data to pass to @function
403  *
404  * Sets a function to be called when the IO condition, as specified by
405  * @condition becomes true for @fd.
406  *
407  * @function will be called when the specified IO condition becomes
408  * %TRUE.  The function is expected to clear whatever event caused the
409  * IO condition to become true and return %TRUE in order to be notified
410  * when it happens again.  If @function returns %FALSE then the watch
411  * will be cancelled.
412  *
413  * The return value of this function can be passed to g_source_remove()
414  * to cancel the watch at any time that it exists.
415  *
416  * The source will never close the fd -- you must do it yourself.
417  *
418  * Returns: the ID (greater than 0) of the event source
419  *
420  * Since: 2.36
421  **/
422 guint
423 g_unix_fd_add (gint              fd,
424                GIOCondition      condition,
425                GUnixFDSourceFunc function,
426                gpointer          user_data)
427 {
428   return g_unix_fd_add_full (G_PRIORITY_DEFAULT, fd, condition, function, user_data, NULL);
429 }