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