#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;
}
|