CIMinuv
CIMinuv

Reputation: 223

can't keep connection socket in apache module

I'm trying to create an Apache module using socket to connect to the other server. It works well and I can retrieve data, but I have encountered three problems.

  1. I can't keep connection with my server (auto close after each request).
  2. I get 2 errors for each request in error log AH00052: child pid 7970 exit signal Segmentation fault (11).
  3. When I continuously press f5 on my browser get error "No data received".

This is my module's code:

#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                      */
};

How can I solve this?

Upvotes: 0

Views: 669

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

Not a definite answer, but I believe you have to use apache pools for resource management in modules.

Upvotes: 1

Related Questions