KWJ2104
KWJ2104

Reputation: 2009

Simple Apache Server Module

I created a simple Apache server module following a sample hello world module I found somewhere. Then I added a variable that would track the number of visits on my page. Here is my module code:

/* The simplest HelloWorld module */
#include <httpd.h>
#include <http_protocol.h>
#include <http_config.h>

static int noOfViews = 0;

static int helloworld_handler(request_rec *r)
{
    noOfViews++;

    if (!r->handler || strcmp(r->handler, "helloworld")) {
        return DECLINED;
    }

    if (r->method_number != M_GET) {
        return HTTP_METHOD_NOT_ALLOWED;
    }

    ap_set_content_type(r, "text/html;charset=ascii");
    ap_rputs("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n",
             r);
    ap_rputs("<html><head><title>Apache HelloWorld "
             "Module</title></head>", r);
    ap_rputs("<body><h1>Hello World!</h1>", r);
    ap_rputs("<p>This is the Apache HelloWorld module!</p>", r);
    ap_rprintf(r, "<p>Views: %d</p>", noOfViews);
    ap_rputs("</body></html>", r);
    return OK;
}

static void helloworld_hooks(apr_pool_t *pool)
{
    ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

module AP_MODULE_DECLARE_DATA helloworld_module = {
    STANDARD20_MODULE_STUFF,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
            helloworld_hooks
};

My module is currently experiencing 2 problems that I am unable to figure out.

  1. My views count seems to go up in multiples of 2 even though I only want it to increment 1 at a time.

  2. When I constantly refresh my page, sometimes my number randomly falls.

Does anyone know what the sources of my problems could be?

Thank you guys so much!

Upvotes: 1

Views: 882

Answers (1)

user149341
user149341

Reputation:

  1. You're incrementing your counter for requests that you don't actually handle.

  2. Each worker process in Apache has its own copy of noOfViews. This applies whether you're using the prefork or worker MPM; it's just more a pronounced issue with prefork.

Upvotes: 2

Related Questions