aft.c: Fix a nasty memory corruption bug in afs_ls on 64 bit archs.
[paraslash.git] / close_on_fork.c
1 /*
2  * Copyright (C) 2005-2006 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 /**
46  * delete one file descriptor from the close-on-fork list
47  *
48  * \param fd the file descriptor to delete
49  *
50  * Noop if \a fd does not belong to the close-on-fork list.
51  */
52 void del_close_on_fork_list(int fd)
53 {
54         struct close_on_fork *cof, *tmp;
55
56         if (!initialized)
57                 return;
58         list_for_each_entry_safe(cof, tmp, &close_on_fork_list, node) {
59                 if (fd != cof->fd)
60                         continue;
61                 list_del(&cof->node);
62                 free(cof);
63         }
64 }
65
66 /**
67  * call close(3) for each fd in the close-on-fork list
68  */
69 void close_listed_fds(void)
70 {
71         struct close_on_fork *cof;
72
73         if (!initialized)
74                 return;
75         list_for_each_entry(cof, &close_on_fork_list, node) {
76                 PARA_DEBUG_LOG("closing fd %d\n", cof->fd);
77                 close(cof->fd);
78         }
79 }