C/C++ - 如何在Apache HTTP Server中创建单例连接模块?
问题描述:
比方说,我有我的apache
模块验证码:C/C++ - 如何在Apache HTTP Server中创建单例连接模块?
#include <iostream>
#include <string>
#include <httpd.h>
#include <http_core.h>
#include <http_protocol.h>
#include <http_request.h>
#include <apr_strings.h>
int count = 0;
static void my_child_init(apr_pool_t *p, server_rec *s)
{
count = 1000; //starts up with this number!
}
static int my_handler(request_rec *r)
{
count++; //Increments here
ap_rputs(std::to_string(count).c_str(), r);
return OK;
}
static void register_hooks(apr_pool_t *pool)
{
ap_hook_child_init(my_child_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_handler(my_handler, NULL, NULL, APR_HOOK_LAST);
}
module AP_MODULE_DECLARE_DATA myserver_module =
{
STANDARD20_MODULE_STUFF,
NULL, // Per-directory configuration handler
NULL, // Merge handler for per-directory configurations
NULL, // Per-server configuration handler
NULL, // Merge handler for per-server configurations
NULL, // Any directives we may have for httpd
register_hooks // Our hook registering function
};
现在,如果我打开浏览器,进入localhost/my_server
我看到我的count
递增每次我刷新我的页面时,创建一个新的HTTP请求Apache
。
1001 //from connection 1
1002 //from connection 1
1003 //from connection 1
1004 //from connection 1
...
我期待的是每次我刷新,我看到了count
递增。但有时我看到apache
可能创造另一个连接和模块再次实例化..我现在有两个相同的连接上运行:
1151 //from connection 1
1152 //from connection 1
1001 // from connection 2
1153 //from connection 1
1002 // from connection 2
1003 // from connection 2
1154 //from connection 1
...
反正我有,防止Apache重新加载相同的模块?
答
大多数Apache MPM /通用配置将创建多个子进程。您可以将它们配置为使用具有多个线程的单个进程,或使用共享内存作为计数器。
以便携方式使用共享内存的最简单方法是依赖于“slotmem”和“slotmem_shm”模块。 mod_proxy_balancer使用这个。另一种方法是直接使用server/scoreboard.c使用共享内存。