本文轉自: http://www.loveopensource.com/?p=18 原文如下: Apache模組開發/用C語言擴充apache(3:一個非常簡單的apache module) by linux_prog 有了上面幾篇文章的基礎,大家自己再下點功夫,應該可以去寫一些簡單的模組了, 下面貼出一個很簡單的apache module,大家一起分析一下。 $ cd /usr/local/apache2.2.4 $ vi mod_c.c
#include <time.h> #include <stdlib.h> #include "apr.h" #include "apr_lib.h" #include "apr_strings.h"
#define APR_WANT_STRFUNC #include "apr_want.h"
#include "httpd.h" #include "http_config.h" #include "http_core.h" #include "http_request.h"
module AP_MODULE_DECLARE_DATA c_module;
static int c_handler(request_rec *r) { r->content_type="text/plain"; ap_rprintf(r,"handler:%s/n",r->handler); ap_rprintf(r,"query string:%s/n",r->args); ap_rprintf(r,"filename:%s/n",r->filename); return OK; } static void register_hooks(apr_pool_t *p) { ap_hook_handler(c_handler, NULL, NULL, APR_HOOK_MIDDLE); }
/* module structure */ module AP_MODULE_DECLARE_DATA c_module = { STANDARD20_MODULE_STUFF, NULL, /* dir config creater */ NULL, /* dir merger — default is to override */ NULL, /* server config */ NULL, /* merge server configs */ NULL, /* command apr_table_t */ register_hooks /* register hooks */ };
|
編譯並安裝這個模組(apache提供的apxs非常好): $ ./bin/apxs -c ./mod_c.c $ ./bin/apxs -a -i -n c mod_c.la 這時apxs會自動幫我們把編譯好的mod_c.so安裝到modules/目錄中,而且httpd.conf中已經把這個module load進去了: [root@cn-weblog apache2.2.4]# grep mod_c conf/httpd.conf LoadModule c_module modules/mod_c.so 測試這個模組: $ ./bin/apachectl stop $ ./bin/apachectl start 在IE中訪問http://myhostname/index.html query=yy IE中會出現: handler:text/html query string:query=yy filename:/usr/local/apache2.2.4/htdocs/index.html 說明該module運行成功。 把上面的module簡單解釋一下。 所有的apache module都必須是這個結構體,裡面要定義各個內容。 /* module structure */ module AP_MODULE_DECLARE_DATA c_module = { STANDARD20_MODULE_STUFF, NULL, /* dir config creater */ NULL, /* dir merger — default is to override */ NULL, /* server config */ NULL, /* merge server configs */ //上面4項都是定義httpd.conf中命令的作用的 NULL, /* command apr_table_t */ //定義在httpd.conf中添加的命令,和各命令的處理函數 register_hooks /* register hooks */ //hooks,定義什麼時候執行我們這個module的相關函數 }; ap_hook_handler(c_handler, NULL, NULL, APR_HOOK_MIDDLE); 表示在處理內容請求時調用我們函數–c_handler |