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