A simple thread-safe page counter (ISAPI extension)

Here is a simple example using an ISAPI extension to create a simple thread-safe page counter. It is written in C.

/*
 *
 * A simple page counter
 *
 * This ISAPI extension writes out the number of times it has been accessed.
 *    NOTE: This code is thread-safe and can be run as an out-of-process
 *          extension.
 *
 */

/* Include ISAPI definitions and constants */
#include <httpext.h>
#include <pthread.h> /* Assuming you are using POSIX threads */

/*  This variable holds the number of times this page has been accessed */
int hits = 0;
pthread_mutex_t hits_mutex;

/* This function is called when the extension is loaded by the web server */
BOOL WINAPI
GetExtensionVersion( HSE_VERSION_INFO *pVer )
{
  /*  Set the extension version */
  pVer->dwExtensionVersion = HSE_VERSION;
  /*  Set a description for the extension */
  strncpy(pVer->lpszExtensionDesc, "A Simple Thread-Safe Page Counter",
	  HSE_MAX_EXT_DLL_NAME_LEN);
  /* Initialize the mutex */
  pthread_mutex_init( &hits_mutex, NULL );

  return TRUE;
}

/*  This function is called when the extension is accessed */
DWORD WINAPI
HttpExtensionProc( LPEXTENSION_CONTROL_BLOCK ecb )
{
  char *header   = "Content-Type: text/html";
  int headerlen  = strlen( header );
  char msg[256];
  int msglen;

  /* Use a server support function to write out a header with our
     additional header information */
  ecb->ServerSupportFunction( ecb->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, 0,
			      &headerlen, (DWORD *)header );

  /* Try to lock the mutex */
  pthread_mutex_lock( &hits_mutex );
  /* Update the number of hits */
  sprintf( msg, "This page has been accessed %d times", ++hits );
  /* Now unlock the mutex */
  pthread_mutex_unlock( &hits_mutex );

  /* Write out the number of accesses */
  msglen = strlen( msg );
  ecb->WriteClient( ecb->ConnID, msg, &msglen,0 );

  /* Return, indicating success */
  return 0;
}
Content Manager [Administrator] 16 December 2005  Permalink  
Download Free Trial

Recent Articles

Other Resources



www.zeus.com