2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <dlezcano at fr.ibm.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #include <sys/epoll.h>
32 struct mainloop_handler
{
33 lxc_mainloop_callback_t callback
;
40 int lxc_mainloop(struct lxc_epoll_descr
*descr
)
43 struct mainloop_handler
*handler
;
44 struct epoll_event events
[MAX_EVENTS
];
48 nfds
= epoll_wait(descr
->epfd
, events
, MAX_EVENTS
, -1);
55 for (i
= 0; i
< nfds
; i
++) {
57 (struct mainloop_handler
*) events
[i
].data
.ptr
;
59 /* If the handler returns a positive value, exit
61 if (handler
->callback(handler
->fd
, handler
->data
,
66 if (lxc_list_empty(&descr
->handlers
))
71 int lxc_mainloop_add_handler(struct lxc_epoll_descr
*descr
, int fd
,
72 lxc_mainloop_callback_t callback
, void *data
)
74 struct epoll_event ev
;
75 struct mainloop_handler
*handler
;
76 struct lxc_list
*item
;
78 handler
= malloc(sizeof(*handler
));
82 handler
->callback
= callback
;
87 ev
.data
.ptr
= handler
;
89 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
90 goto out_free_handler
;
92 item
= malloc(sizeof(*item
));
94 goto out_free_handler
;
97 lxc_list_add(&descr
->handlers
, item
);
105 int lxc_mainloop_del_handler(struct lxc_epoll_descr
*descr
, int fd
)
107 struct mainloop_handler
*handler
;
108 struct lxc_list
*iterator
;
110 lxc_list_for_each(iterator
, &descr
->handlers
) {
111 handler
= iterator
->elem
;
113 if (handler
->fd
== fd
) {
115 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_DEL
, fd
, NULL
))
118 lxc_list_del(iterator
);
119 free(iterator
->elem
);
128 int lxc_mainloop_open(struct lxc_epoll_descr
*descr
)
130 /* hint value passed to epoll create */
131 descr
->epfd
= epoll_create(2);
135 lxc_list_init(&descr
->handlers
);
139 int lxc_mainloop_close(struct lxc_epoll_descr
*descr
)
141 struct lxc_list
*iterator
, *next
;
143 iterator
= descr
->handlers
.next
;
144 while (iterator
!= &descr
->handlers
) {
145 next
= iterator
->next
;
147 lxc_list_del(iterator
);
148 free(iterator
->elem
);
153 return close(descr
->epfd
);