Refactoring read/write handlers and pointers
[MonkeyD.git] / src / server.c
blob23748711d6916ae8c9b3b8e5abd18fcdbfdc4d70
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
3 /* Monkey HTTP Daemon
4 * ------------------
5 * Copyright (C) 2001-2008, Eduardo Silva P.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Library General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 #include <stdio.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
26 #include <sys/time.h>
27 #include <sys/resource.h>
29 #include "monkey.h"
30 #include "config.h"
31 #include "scheduler.h"
32 #include "epoll.h"
33 #include "socket.h"
35 /* Return the number of clients that can be attended
36 * at the same time per worker thread
38 int mk_server_worker_capacity(int nworkers)
40 int max, avl;
41 struct rlimit lim;
43 /* Limit by system */
44 getrlimit(RLIMIT_NOFILE, &lim);
45 max = lim.rlim_cur;
47 /* Minimum of fds needed by Monkey:
48 * --------------------------------
49 * 3 fds: stdin, stdout, stderr
50 * 1 fd for main socket server
51 * 1 fd for epoll array (per thread)
52 * 1 fd for worker logger when writing to FS
53 * 2 fd for worker logger pipe
56 avl = max - (3 + 1 + nworkers + 1 + 2);
57 return (avl/nworkers);
60 /* Here we launch the worker threads to attend clients */
61 void mk_server_launch_workers()
63 int i;
65 config->worker_capacity = mk_server_worker_capacity(config->workers);
67 for(i=0; i<config->workers; i++)
69 mk_sched_launch_thread(config->worker_capacity);
73 void mk_server_loop(int server_fd)
75 int remote_fd;
76 struct sockaddr_in sockaddr;
77 struct sched_list_node *sched = sched_list;
78 socklen_t socket_size = sizeof(struct sockaddr_in);
80 while(1){
81 remote_fd = accept(server_fd, (struct sockaddr *)&sockaddr,
82 &socket_size);
84 if(remote_fd == -1){
85 continue;
88 /* Assign socket to worker thread */
89 mk_sched_add_client(sched, remote_fd);
91 if(sched->next){
92 sched = sched->next;
94 else{
95 sched = sched_list;