Based on the previous articles Apache hook mechanism resolution (I)-Implementation of hook mechanism and Apache hook mechanism resolution (medium)-detail discussion, we have learned a lot about the Apache hook mechanism. The following Code demonstrates how to declare, define, and use a Log Hook. It is compiled and tested on vc6.0, you need to use the APR Library (libapr and libaprutils ). 1. hooklog. h -- declare a hook named log # ifndef _ hook_log_h __
# DEFINE _ hook_log_h __
# Ifdef _ cplusplus
Extern "C "{
# Endif
# Include "apr_hooks.h"
# Define my_declare (type) Type
Apr_declare_external_hook (My, my, Int, log, (const char * sztext ))
# Ifdef _ cplusplus
}
# Endif 2. hooklog. c -- Define a hook named log # include "hooklog. H"
// Define the hook structure variable named log
Apr_hook_struct (
Apr_hook_link (log)
)
// Define log-related hook implementation. Here 0 is used as OK and-1 is used as decline.
Apr_implement_external_hook_run_all (My, my, Int, log, (const char * sztext), (sztext), 0,-1) 3. test. C -- mount the hook and trigger # include "hooklog. h"
# Include "apr_pools.h"
/* File log implementation */
Static int filelog (const char * sztext)
{
File * fp = NULL;
Fp = fopen ("filelog.txt", "WT ");
If (FP ){
Fseek (FP, 0, seek_end );
Fprintf (FP, "% s/n", sztext );
Fclose (FP );
}
Return 0;
}
/* Console log implementation */
Static int consolelog (const char * sztext)
{
Printf ("% s/n", sztext );
Return 0;
}
Int main ()
{
// Initialize the APR Library and the global memory pool required by the hook
Apr_initialize ();
Apr_pool_create (& apr_hook_global_pool, null );
// Mount the hook
My_hook_log (consolelog, null, null, apr_hook_middle );
My_hook_log (filelog, null, null, apr_hook_middle );
// Sort the hooks. apr_sort_all_hooks (); // trigger the hook. This call will trigger two mounted hooks: filelog and consolelog.
My_run_log ("Hello world! ");
// Destroy the memory pool
Apr_pool_destroy (apr_hook_global_pool );
Return 0;
}