2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include <sys/epoll.h>
34 struct mainloop_handler
{
35 lxc_mainloop_callback_t callback
;
42 int lxc_mainloop(struct lxc_epoll_descr
*descr
, int timeout_ms
)
45 struct mainloop_handler
*handler
;
46 struct epoll_event events
[MAX_EVENTS
];
49 nfds
= epoll_wait(descr
->epfd
, events
, MAX_EVENTS
, timeout_ms
);
57 for (i
= 0; i
< nfds
; i
++) {
58 handler
= events
[i
].data
.ptr
;
60 /* If the handler returns a positive value, exit the
63 ret
= handler
->callback(handler
->fd
, events
[i
].events
,
64 handler
->data
, descr
);
65 if (ret
== LXC_MAINLOOP_CLOSE
)
72 if (lxc_list_empty(&descr
->handlers
))
77 int lxc_mainloop_add_handler(struct lxc_epoll_descr
*descr
, int fd
,
78 lxc_mainloop_callback_t callback
, void *data
)
80 struct epoll_event ev
;
81 struct mainloop_handler
*handler
;
82 struct lxc_list
*item
;
84 handler
= malloc(sizeof(*handler
));
88 handler
->callback
= callback
;
93 ev
.data
.ptr
= handler
;
95 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
96 goto out_free_handler
;
98 item
= malloc(sizeof(*item
));
100 goto out_free_handler
;
102 item
->elem
= handler
;
103 lxc_list_add(&descr
->handlers
, item
);
111 int lxc_mainloop_del_handler(struct lxc_epoll_descr
*descr
, int fd
)
113 struct mainloop_handler
*handler
;
114 struct lxc_list
*iterator
;
116 lxc_list_for_each(iterator
, &descr
->handlers
) {
117 handler
= iterator
->elem
;
119 if (handler
->fd
== fd
) {
121 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_DEL
, fd
, NULL
))
124 lxc_list_del(iterator
);
125 free(iterator
->elem
);
134 int lxc_mainloop_open(struct lxc_epoll_descr
*descr
)
136 /* hint value passed to epoll create */
137 descr
->epfd
= epoll_create(2);
141 if (fcntl(descr
->epfd
, F_SETFD
, FD_CLOEXEC
)) {
146 lxc_list_init(&descr
->handlers
);
150 int lxc_mainloop_close(struct lxc_epoll_descr
*descr
)
152 struct lxc_list
*iterator
, *next
;
154 iterator
= descr
->handlers
.next
;
155 while (iterator
!= &descr
->handlers
) {
156 next
= iterator
->next
;
158 lxc_list_del(iterator
);
159 free(iterator
->elem
);
164 return close(descr
->epfd
);