想用c语言实现类似glib mainloop那样的事件循环机制,求思路或方向,谢谢各位大神!
struct pollfd fds[2];
int timeout_msecs = 500;
int ret;
int i;
/ Open STREAMS device. /
fds[0].fd = open("/dev/dev0", ...);
fds[1].fd = open("/dev/dev1", ...);
fds[0].events = POLLOUT | POLLWRBAND;
fds[1].events = POLLOUT | POLLWRBAND;
while(1) {
ret = poll(fds, 2, timeout_msecs);
if (ret > 0) {
/ An event on one of the fds has occurred. /
for (i=0; i<2; i++) {
if (fds[i].revents & POLLWRBAND) {
/ Priority data may be written on device number i. /
...
}
if (fds[i].revents & POLLOUT) {
/ Data may be written on device number i. /
...
}
if (fds[i].revents & POLLHUP) {
/ A hangup has occurred on device number i. /
...
}
}
}
}
struct pollfd fds[2];
int timeout_msecs = 500;
int ret;
int i;
/ Open STREAMS device. /
fds[0].fd = open("/dev/dev0", ...);
fds[1].fd = open("/dev/dev1", ...);
fds[0].events = POLLOUT | POLLWRBAND;
fds[1].events = POLLOUT | POLLWRBAND;
while(1) {
ret = poll(fds, 2, timeout_msecs);
if (ret > 0) {
/ An event on one of the fds has occurred. /
for (i=0; i<2; i++) {
if (fds[i].revents & POLLWRBAND) {
/ Priority data may be written on device number i. /
...
}
if (fds[i].revents & POLLOUT) {
/ Data may be written on device number i. /
...
}
if (fds[i].revents & POLLHUP) {
/ A hangup has occurred on device number i. /
...
}
}
}
}
struct pollfd fds[2];
int timeout_msecs = 500;
int ret;
int i;
/ Open STREAMS device. /
fds[0].fd = open("/dev/dev0", ...);
fds[1].fd = open("/dev/dev1", ...);
fds[0].events = POLLOUT | POLLWRBAND;
fds[1].events = POLLOUT | POLLWRBAND;
while(1) {
ret = poll(fds, 2, timeout_msecs);
if (ret > 0) {
/* An event on one of the fds has occurred. */
for (i=0; i<2; i++) {
if (fds[i].revents & POLLWRBAND) {
/* Priority data may be written on device number i. */
...
}
if (fds[i].revents & POLLOUT) {
/* Data may be written on device number i. */
...
}
if (fds[i].revents & POLLHUP) {
/* A hangup has occurred on device number i. */
...
}
}
}
}
你首先要确定是哪类的 EVENT。
好吧,我来做一个通用的回答。
通畅,在 linux 端,我们会使用 epoll 函数来做事件循环:
如下举例:
一个很 ugly (但有效)的解决方案:
定义一个 struct Event 的队列
struct Event event;
while (1)
{
if (empty(event_queue))
sleep(WAITING);
else {
event = get_first_element(event_queue);
remove_first_element(event_queue);
process...
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。