0
我試圖使用套接字創建一個Apache模塊來連接到其他服務器。它運行良好,我可以檢索數據,但我遇到了三個問題。無法在apache模塊中保留連接套接字
- 我無法與我的服務器保持連接(每次請求後自動關閉)。
- 對於錯誤日誌
AH00052: child pid 7970 exit signal Segmentation fault (11)
中的每個請求,我得到2個錯誤。 - 當我在瀏覽器上連續按f5時出現錯誤「未收到數據」。
這是我的模塊的代碼:
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/select.h>
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
static int sockfd = -1;
static struct sockaddr_in saddr;
/* The sample content handler */
static int search_handler(request_rec *r)
{
r->content_type = "text/html";
ap_rprintf(r,"sockfd = %d<br>", sockfd);
if(sockfd == -1){
sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct hostent *server = gethostbyname("127.0.0.1");
if(server == NULL) return DECLINED;
bzero((char *) &saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&saddr.sin_addr.s_addr,server->h_length);
saddr.sin_port = htons(9999);
if(sockfd == -1) return DECLINED;
if(connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0){
ap_rputs("Can't connect.\n", r);
return OK;
}
}
send(sockfd, r->args, strlen(r->args), 0);
fd_set read_sd;
FD_ZERO(&read_sd);
FD_SET(sockfd, &read_sd);
int sel = select(sockfd + 1, &read_sd, 0, 0, 0);
if(sel < 0) {close(sockfd);return DECLINED;}
if(sel == 0) {ap_rprintf(r, "time out."); return OK;}
char buf[5000];
if(recv(sockfd, buf, 5000, 0) <= 0) return DECLINED;
ap_rprintf(r, "%s<br>%d", buf, sockfd);
return OK;
}
static void search_register_hooks(apr_pool_t *p)
{
ap_hook_handler(search_handler, NULL, NULL, APR_HOOK_LAST);
}
/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA search_module = {
STANDARD20_MODULE_STUFF,
NULL, /* create per-dir config structures */
NULL, /* merge per-dir config structures */
NULL, /* create per-server config structures */
NULL, /* merge per-server config structures */
NULL, /* table of config file commands */
search_register_hooks /* register hooks */
};
我怎樣才能解決這個問題?
你的意思是我必須分配sockfd作爲動態變量而不是靜態變量? – CIMinuv 2012-08-07 08:22:56
我不是apache的專業人士,但我認爲你必須註冊一個池或其他東西,並給它一個解除分配的功能(如在這種情況下'close')。 – 2012-08-07 12:13:00