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
29 #include <sys/epoll.h>
33 struct mainloop_handler
{
34 lxc_mainloop_callback_t callback
;
41 int lxc_mainloop(struct lxc_epoll_descr
*descr
, int timeout_ms
)
44 struct mainloop_handler
*handler
;
45 struct epoll_event events
[MAX_EVENTS
];
49 nfds
= epoll_wait(descr
->epfd
, events
, MAX_EVENTS
, timeout_ms
);
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
, events
[i
].events
,
63 handler
->data
, descr
) > 0)
67 if (nfds
== 0 && timeout_ms
!= 0)
70 if (lxc_list_empty(&descr
->handlers
))
75 int lxc_mainloop_add_handler(struct lxc_epoll_descr
*descr
, int fd
,
76 lxc_mainloop_callback_t callback
, void *data
)
78 struct epoll_event ev
;
79 struct mainloop_handler
*handler
;
80 struct lxc_list
*item
;
82 handler
= malloc(sizeof(*handler
));
86 handler
->callback
= callback
;
91 ev
.data
.ptr
= handler
;
93 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
94 goto out_free_handler
;
96 item
= malloc(sizeof(*item
));
98 goto out_free_handler
;
100 item
->elem
= handler
;
101 lxc_list_add(&descr
->handlers
, item
);
109 int lxc_mainloop_del_handler(struct lxc_epoll_descr
*descr
, int fd
)
111 struct mainloop_handler
*handler
;
112 struct lxc_list
*iterator
;
114 lxc_list_for_each(iterator
, &descr
->handlers
) {
115 handler
= iterator
->elem
;
117 if (handler
->fd
== fd
) {
119 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_DEL
, fd
, NULL
))
122 lxc_list_del(iterator
);
123 free(iterator
->elem
);
132 int lxc_mainloop_open(struct lxc_epoll_descr
*descr
)
134 /* hint value passed to epoll create */
135 descr
->epfd
= epoll_create(2);
139 if (fcntl(descr
->epfd
, F_SETFD
, FD_CLOEXEC
)) {
144 lxc_list_init(&descr
->handlers
);
148 int lxc_mainloop_close(struct lxc_epoll_descr
*descr
)
150 struct lxc_list
*iterator
, *next
;
152 iterator
= descr
->handlers
.next
;
153 while (iterator
!= &descr
->handlers
) {
154 next
= iterator
->next
;
156 lxc_list_del(iterator
);
157 free(iterator
->elem
);
162 return close(descr
->epfd
);