我正在尝试使用套接字创建一个 Apache 模块以连接到另一台服务器。它运行良好,我可以检索数据,但我遇到了三个问题。
- 我无法与我的服务器保持连接(每次请求后自动关闭)。
- 对于错误日志中的每个请求,我都会收到 2 个错误
AH00052: child pid 7970 exit signal Segmentation fault (11)
。 - 当我在浏览器上连续按 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 */
};
我该如何解决这个问题?