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
29 #include <sys/epoll.h>
33 struct mainloop_handler
{
34 lxc_mainloop_callback_t callback
;
41 int lxc_mainloop(struct lxc_epoll_descr
*descr
)
44 struct mainloop_handler
*handler
;
45 struct epoll_event events
[MAX_EVENTS
];
49 nfds
= epoll_wait(descr
->epfd
, events
, MAX_EVENTS
, -1);
56 for (i
= 0; i
< nfds
; i
++) {
58 (struct mainloop_handler
*) events
[i
].data
.ptr
;
60 /* If the handler returns a positive value, exit
62 if (handler
->callback(handler
->fd
, handler
->data
,
67 if (lxc_list_empty(&descr
->handlers
))
72 int lxc_mainloop_add_handler(struct lxc_epoll_descr
*descr
, int fd
,
73 lxc_mainloop_callback_t callback
, void *data
)
75 struct epoll_event ev
;
76 struct mainloop_handler
*handler
;
77 struct lxc_list
*item
;
79 handler
= malloc(sizeof(*handler
));
83 handler
->callback
= callback
;
88 ev
.data
.ptr
= handler
;
90 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
91 goto out_free_handler
;
93 item
= malloc(sizeof(*item
));
95 goto out_free_handler
;
98 lxc_list_add(&descr
->handlers
, item
);
106 int lxc_mainloop_del_handler(struct lxc_epoll_descr
*descr
, int fd
)
108 struct mainloop_handler
*handler
;
109 struct lxc_list
*iterator
;
111 lxc_list_for_each(iterator
, &descr
->handlers
) {
112 handler
= iterator
->elem
;
114 if (handler
->fd
== fd
) {
116 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_DEL
, fd
, NULL
))
119 lxc_list_del(iterator
);
120 free(iterator
->elem
);
129 int lxc_mainloop_open(struct lxc_epoll_descr
*descr
)
131 /* hint value passed to epoll create */
132 descr
->epfd
= epoll_create(2);
136 if (fcntl(descr
->epfd
, F_SETFD
, FD_CLOEXEC
)) {
141 lxc_list_init(&descr
->handlers
);
145 int lxc_mainloop_close(struct lxc_epoll_descr
*descr
)
147 struct lxc_list
*iterator
, *next
;
149 iterator
= descr
->handlers
.next
;
150 while (iterator
!= &descr
->handlers
) {
151 next
= iterator
->next
;
153 lxc_list_del(iterator
);
154 free(iterator
->elem
);
159 return close(descr
->epfd
);