Merge commit 'fml/master'
[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 #include "para.h"
9 #include "list.h"
10 #include "string.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 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 /**
66  * Call close(3) for each fd in the close-on-fork list.
67  */
68 void close_listed_fds(void)
69 {
70         struct close_on_fork *cof;
71
72         if (!initialized)
73                 return;
74         list_for_each_entry(cof, &close_on_fork_list, node) {
75                 PARA_DEBUG_LOG("closing fd %d\n", cof->fd);
76                 close(cof->fd);
77         }
78 }