Skip to content

Commit

Permalink
added a ctrl-c handler that stops the server cleanly
Browse files Browse the repository at this point in the history
  • Loading branch information
tsliwowicz committed May 27, 2013
1 parent 19bba32 commit d7e1297
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
14 changes: 11 additions & 3 deletions main.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <apr-1.0/apr_time.h>
#include <signal.h>
#include <unistd.h>
#include "http-server.h"

#define json_output "{\"message\":\"Hello, World!\"}"
Expand All @@ -28,7 +29,6 @@ static void json_handler(struct evhttp_request *req);
static void xml_handler(struct evhttp_request *req);

//TODO: add - generic handler
//TODO: add - files handler
static http_handler_t handlers[] = {
{json_handler, "/json"},
{xml_handler, "/xml"}
Expand Down Expand Up @@ -70,16 +70,24 @@ void json_handler(struct evhttp_request *req)
evbuffer_free(rep_buf);
}

static void ctrl_c_handler(int sig)
{
http_server_stop(0);
}

int main(int c, char **v)
{
http_server_init();
http_server_start(8080, handlers, NUM_HANDLERS, "/var/www");
signal (SIGINT,ctrl_c_handler);

while (http_server_is_active())
{
apr_sleep(APR_USEC_PER_SEC/100); //10 ms
usleep(10000); //10 ms
}

fprintf(stderr, "bye bye\n");

http_server_cleanup();
return(0);
}
11 changes: 7 additions & 4 deletions src/http-server.c
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ int http_server_start(unsigned short port, http_handler_t http_handlers[], int n

num_servers = num_cpus;

server_base = apr_pcalloc(global_pool, num_servers * sizeof(struct event_base *));
server_base = apr_pcalloc(global_pool, (num_servers + 1) * sizeof(struct event_base *));

for(i= 0; i < num_servers; i++)
{
Expand All @@ -328,11 +328,14 @@ int http_server_start(unsigned short port, http_handler_t http_handlers[], int n

void http_server_stop(int to_wait)
{
int i;
for(i= 0; i < num_servers; i++)
int i, n = apr_atomic_read32(&num_servers);
for(i= 0; i < n; i++)
{
if (server_base[i])
{
event_base_loopbreak(server_base[i]);
server_base[i] = NULL;
}
}

if (to_wait)
Expand Down Expand Up @@ -411,8 +414,8 @@ void *http_server(apr_thread_t* t, void* d)
}
if (base)
{
server_base[server_data->server_index] = NULL;
event_base_free(base);
server_base[server_data->server_index] = NULL;
}

apr_atomic_dec32(&num_servers);
Expand Down

0 comments on commit d7e1297

Please sign in to comment.