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
32 #include <sys/epoll.h>
38 struct mainloop_handler
{
39 lxc_mainloop_callback_t callback
;
46 int lxc_mainloop(struct lxc_epoll_descr
*descr
, int timeout_ms
)
49 struct mainloop_handler
*handler
;
50 struct epoll_event events
[MAX_EVENTS
];
53 nfds
= epoll_wait(descr
->epfd
, events
, MAX_EVENTS
, timeout_ms
);
61 for (i
= 0; i
< nfds
; i
++) {
62 handler
= events
[i
].data
.ptr
;
64 /* If the handler returns a positive value, exit the
67 ret
= handler
->callback(handler
->fd
, events
[i
].events
,
68 handler
->data
, descr
);
69 if (ret
== LXC_MAINLOOP_CLOSE
)
76 if (lxc_list_empty(&descr
->handlers
))
81 int lxc_mainloop_add_handler(struct lxc_epoll_descr
*descr
, int fd
,
82 lxc_mainloop_callback_t callback
, void *data
)
84 struct epoll_event ev
;
85 struct mainloop_handler
*handler
;
86 struct lxc_list
*item
;
88 handler
= malloc(sizeof(*handler
));
92 handler
->callback
= callback
;
97 ev
.data
.ptr
= handler
;
99 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
100 goto out_free_handler
;
102 item
= malloc(sizeof(*item
));
104 goto out_free_handler
;
106 item
->elem
= handler
;
107 lxc_list_add(&descr
->handlers
, item
);
115 int lxc_mainloop_del_handler(struct lxc_epoll_descr
*descr
, int fd
)
117 struct mainloop_handler
*handler
;
118 struct lxc_list
*iterator
;
120 lxc_list_for_each(iterator
, &descr
->handlers
) {
121 handler
= iterator
->elem
;
123 if (handler
->fd
== fd
) {
125 if (epoll_ctl(descr
->epfd
, EPOLL_CTL_DEL
, fd
, NULL
))
128 lxc_list_del(iterator
);
129 free(iterator
->elem
);
138 int lxc_mainloop_open(struct lxc_epoll_descr
*descr
)
140 /* hint value passed to epoll create */
141 descr
->epfd
= epoll_create1(EPOLL_CLOEXEC
);
145 lxc_list_init(&descr
->handlers
);
149 int lxc_mainloop_close(struct lxc_epoll_descr
*descr
)
151 struct lxc_list
*iterator
, *next
;
153 iterator
= descr
->handlers
.next
;
154 while (iterator
!= &descr
->handlers
) {
155 next
= iterator
->next
;
157 lxc_list_del(iterator
);
158 free(iterator
->elem
);
163 if (descr
->epfd
>= 0)
164 return close(descr
->epfd
);