2017-11-25 142 views
0

比方說,我有我的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重新加載相同的模塊?

回答

1

大多數Apache MPM /通用配置將創建多個子進程。您可以將它們配置爲使用具有多個線程的單個進程,或使用共享內存作爲計數器。

以便攜方式使用共享內存的最簡單方法是依賴於「slotmem」和「slotmem_shm」模塊。 mod_proxy_balancer使用這個。另一種方法是直接使用server/scoreboard.c使用共享內存。