Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1096536
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类: BSD

2009-08-28 14:04:03

#include <sys/types.h>
#include <netinet/in.h>
#include <sys/event.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define err(msg) perror(msg)
#define SA struct sockaddr

struct event
{
        int fd;
        void (*handle)(struct event *);
};

static int tcp_listen(void)
{
        struct sockaddr_in addr;
        int fd;

        if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
        {
                err("socket");
                return -1;
        }

        memset(&addr, '\0', sizeof(struct sockaddr_in));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(8888);
        if (inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr) <= 0)
        {
                err("inet_pton");
                goto err;
        }

        if (bind(fd, (SA *)&addr, sizeof(struct sockaddr_in)) == -1)
        {
                err("bind");
                goto err;
        }

        if (listen(fd, 10) == -1)
        {
                err("listen");
                goto err;
        }

        return fd;
err:
        close(fd);
        return -1;
}

static void listen_readable(struct event *e)
{
        int connfd;

        connfd = accept(e->fd, NULL, NULL);
        printf("connfd = %d\n", connfd);
        close(connfd);
}

int main(void)
{
        int fd;
        int kq;
        int nfds;
        struct kevent ev, rev[2];

        if ((fd = tcp_listen()) == -1)
        {
                err("tcp_listen");
                return -1;
        }

        if ((kq = kqueue()) == -1)
        {
                err("kqueue");
                goto err;
        }

        struct event e;

        e.fd = fd;
        e.handle = listen_readable;

        EV_SET(&ev, fd, EVFILT_READ, EV_ADD, 0, 0, &e);

        while (1)
        {
                nfds = kevent(kq, &ev, 1, rev, 2, NULL);
                if (nfds <= 0)
                {
                        err("kevent");
                        goto kevent_err;
                }

                for (int i = 0; i < nfds; i++)
                {
                        struct event *re = rev[i].udata;
                        if (re)
                                re->handle(re);
                }
        }

        return 0;
kevent_err:
        close(kq);
err:
        close(fd);
        return -1;
}

阅读(775) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~