-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
50 lines (38 loc) · 1.24 KB
/
main.c
File metadata and controls
50 lines (38 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <sys/event.h>
#include "http.h"
int main(){
ServerConfig config;
if (parse_config("config.conf", &config) == -1) return 1;
int sockfd = create_server(config.port);
if (sockfd == -1) return 1;
printf("Server started on port %d, root: %s\n", config.port, config.root);
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int kq = kqueue();
struct kevent ev;
EV_SET(&ev,sockfd, EVFILT_READ, EV_ADD, 0, 0, NULL);
kevent(kq, &ev, 1, NULL,0,NULL);
struct kevent events[128];
while (1) {
int n = kevent(kq, NULL, 0, events, 128, NULL);
for (int i =0;i< n; i++){
int fd = events[i].ident;
if (fd == sockfd) {
int clientfd = accept(sockfd, (struct sockaddr *) &client_addr, &client_len);
struct kevent ev;
EV_SET(&ev, clientfd, EVFILT_READ, EV_ADD, 0, 0, NULL);
kevent(kq, &ev, 1, NULL, 0, NULL);
}else{
if(!handle_client(fd, &config)){
close(fd);
}
}
}
}
close(sockfd);
}