manual: Fix package name of flac library.
[paraslash.git] / close_on_fork.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file close_on_fork.c Manage a list of fds that should be closed on fork. */
4
5 #include <regex.h>
6
7 #include "para.h"
8 #include "list.h"
9 #include "string.h"
10 #include "close_on_fork.h"
11
12 static struct list_head close_on_fork_list;
13 static int initialized;
14
15 /**
16  * Describes an element of the close-on-fork list.
17  *
18  * \sa \ref list.h.
19  */
20 struct close_on_fork {
21         /** The file descriptor which should be closed after fork(). */
22         int fd;
23         /** The position in the close-on-fork list. */
24         struct list_head node;
25 };
26
27 /**
28  * Add one file descriptor to the close-on-fork list.
29  *
30  * \param fd The file descriptor to add.
31  */
32 void add_close_on_fork_list(int fd)
33 {
34         struct close_on_fork *cof = para_malloc(sizeof(struct close_on_fork));
35
36         if (!initialized) {
37                 INIT_LIST_HEAD(&close_on_fork_list);
38                 initialized = 1;
39         }
40         cof->fd = fd;
41         para_list_add(&cof->node, &close_on_fork_list);
42 }
43
44 /**
45  * Delete one file descriptor from the close-on-fork list.
46  *
47  * \param fd The file descriptor to delete.
48  *
49  * Noop if \a fd does not belong to the close-on-fork list.
50  */
51 void del_close_on_fork_list(int fd)
52 {
53         struct close_on_fork *cof, *tmp;
54
55         if (!initialized)
56                 return;
57         list_for_each_entry_safe(cof, tmp, &close_on_fork_list, node) {
58                 if (fd != cof->fd)
59                         continue;
60                 list_del(&cof->node);
61                 free(cof);
62         }
63 }
64
65 static void deplete_cof_list(bool close_fds)
66 {
67         struct close_on_fork *cof, *tmp;
68
69         if (!initialized)
70                 return;
71         list_for_each_entry_safe(cof, tmp, &close_on_fork_list, node) {
72                 PARA_DEBUG_LOG("closing fd %d\n", cof->fd);
73                 if (close_fds)
74                         close(cof->fd);
75                 list_del(&cof->node);
76                 free(cof);
77         }
78 }
79
80 /**
81  * Close all fds in the list and destroy all list entries.
82  *
83  * This function calls close(3) for each fd in the close-on-fork list
84  * and empties the list afterwards.
85  *
86  * \sa \ref deplete_close_on_fork_list().
87  */
88 void close_listed_fds(void)
89 {
90         deplete_cof_list(true);
91 }
92
93 /**
94  * Remove all listed fds from the close on fork list.
95  *
96  * This is like \ref close_listed_fds() but does not close the fds.
97  */
98 void deplete_close_on_fork_list(void)
99 {
100         deplete_cof_list(false);
101 }