Merge commit 'fml/master' into next
[paraslash.git] / close_on_fork.c
1 /*
2 * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file close_on_fork.c Manage a list of fds that should be closed on fork. */
8
9 #include <regex.h>
10
11 #include "para.h"
12 #include "list.h"
13 #include "string.h"
14
15 static struct list_head close_on_fork_list;
16 static int initialized;
17
18 /**
19 * Describes an element of the close-on-fork list.
20 *
21 * \sa list.h
22 */
23 struct close_on_fork {
24 /** The file descriptor which should be closed after fork(). */
25 int fd;
26 /** The position in the close-on-fork list. */
27 struct list_head node;
28 };
29
30 /**
31 * Add one file descriptor to the close-on-fork list.
32 *
33 * \param fd The file descriptor to add.
34 */
35 void add_close_on_fork_list(int fd)
36 {
37 struct close_on_fork *cof = para_malloc(sizeof(struct close_on_fork));
38
39 if (!initialized) {
40 INIT_LIST_HEAD(&close_on_fork_list);
41 initialized = 1;
42 }
43 cof->fd = fd;
44 para_list_add(&cof->node, &close_on_fork_list);
45 }
46
47 /**
48 * Delete one file descriptor from the close-on-fork list.
49 *
50 * \param fd The file descriptor to delete.
51 *
52 * Noop if \a fd does not belong to the close-on-fork list.
53 */
54 void del_close_on_fork_list(int fd)
55 {
56 struct close_on_fork *cof, *tmp;
57
58 if (!initialized)
59 return;
60 list_for_each_entry_safe(cof, tmp, &close_on_fork_list, node) {
61 if (fd != cof->fd)
62 continue;
63 list_del(&cof->node);
64 free(cof);
65 }
66 }
67
68 /**
69 * Close all fds in the list and destroy all list entries.
70 *
71 * This function calls close(3) for each fd in the close-on-fork list
72 * and empties the list afterwards.
73 */
74 void close_listed_fds(void)
75 {
76 struct close_on_fork *cof, *tmp;
77
78 if (!initialized)
79 return;
80 list_for_each_entry_safe(cof, tmp, &close_on_fork_list, node) {
81 PARA_DEBUG_LOG("closing fd %d\n", cof->fd);
82 close(cof->fd);
83 list_del(&cof->node);
84 free(cof);
85 }
86 }