Esempio n. 1
0
int main(int argc, char **argv)
{
	int retval;
	void *handle = NULL;
	short	http_port = 8081;
	// Binds on IPv4 & IPv6, refer to /proc/sys/net/ipv6/bindv6only
	char	*http_addr = "::";
	struct	evhttp *http_server = NULL;

	cweb_init();
	retval = init_pages();
	if (retval) {
		printf("[ERROR] loading of plugins failed.\n");
		return EXIT_FAILURE;
	}

	event_init();
	http_server = evhttp_start(http_addr, http_port);
	evhttp_set_gencb(http_server, cweb_request_handler, NULL);

	fprintf(stderr, "Server started on port %d\n", http_port);
	event_dispatch();

	return(0);
}
Esempio n. 2
0
int
main(int argc, char **argv)
{
  // initialize libraries
  struct evhttp *httpd;

  if (sigignore(SIGPIPE) == -1) {
    perror("failed to ignore SIGPIPE; sigaction");
    exit(EXIT_FAILURE);
  }

  host = argv[2];
  port = atoi(argv[3]);
  event_init();
  httpd = evhttp_start("0.0.0.0", atoi(argv[1]));
  if (httpd == NULL) {
    perror("evhttpd failed!");
    exit(1);
  }

  /* Set a callback for all other requests. */
  evhttp_set_gencb(httpd, proxycb, NULL);

  event_dispatch();
  /* Not reached in this code as it is now. */
  evhttp_free(httpd);

  return EXIT_SUCCESS;
}
Esempio n. 3
0
void *CHttpServer::http_start_server(void *arg)
{
	CHttpServer *pthis = (CHttpServer *)arg;
	struct evhttp *httpd = NULL;
    	
	event_init();
	httpd = evhttp_start(pthis->m_http_addr, pthis->m_http_port);
	if (NULL == httpd) {
           printf("http server unable to listen on %s:%d\n\n", pthis->m_http_addr, pthis->m_http_port);
	   return NULL; 
    }
    evhttp_set_timeout(httpd, pthis->m_timeout);       
    evhttp_set_gencb(httpd, http_handle_postdata, arg);

#ifdef DEBUG
	printf("http_server start:%s:%d timeout:%u\n", 
			pthis->m_http_addr, 
			pthis->m_http_port, 
			pthis->m_timeout);
#else
	logrun("http_server start:%s:%d timeout:%u", 
			pthis->m_http_addr, 
			pthis->m_http_port, 
			pthis->m_timeout);
#endif
	event_dispatch();
	evhttp_free(httpd);
	
	return NULL;
}
Esempio n. 4
0
int main(int argc, char **argv)
{
    setting = &_setting;
    sigset_t signal_mask;
    sigemptyset(&signal_mask);
    sigaddset(&signal_mask, SIGPIPE);
    pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);

    signal(SIGINT, clean_up);
    signal(SIGQUIT, clean_up);
    signal(SIGTERM, clean_up);

    parse_options(argc, argv);

    if (setting->daemon_mode) {
        daemonize();
    }
    redis_init(setting->redis_addr, setting->redis_port);
    event_init();
    config_init();

    g_httpd = evhttp_start(setting->listen_host, setting->listen_port);
    evhttp_set_gencb(g_httpd, request_handler, NULL);
    event_dispatch();

    return 0;
}
Esempio n. 5
0
int main(int argc, char **argv)
{
	struct evhttp *httpd;

	event_init();
	httpd = evhttp_start(argv[argc-2], atoi(argv[argc-1]));
	evhttp_set_cb(httpd, "/request_sys/", sys_handler, NULL); 
/* Set a callback for all other requests. */
	evhttp_set_gencb(httpd, notfound_hander, NULL);
event_dispatch();    /* Not reached in this code as it is now. */
	evhttp_free(httpd);    
	return 0;
}
Esempio n. 6
0
bool Server::run( const std::string &ip, const std::uint32_t &port)
{
    if (!event_init())
        return false;

    std::unique_ptr< evhttp, decltype(&evhttp_free)> resmServer( evhttp_start( ip.c_str(), port), &evhttp_free);
    if (!resmServer)
        return false;

    std::cout << "Server run "<< ip << ":" << port << std::endl;

    evhttp_set_gencb( resmServer.get(), Server::requestHandler, (void*)this);
    if (event_dispatch() == -1)
        return false;

    return true;
}
Esempio n. 7
0
int main(int argc, char **argv)
{
	short http_port = 8080;
	char *http_addr = "localhost";
	struct evhttp *http_server = NULL;

	event_init();
	http_server = evhttp_start(http_addr, http_port);
	evhttp_set_gencb(http_server, generic_request_handler, NULL);

	printf("Server started on port %d\n", http_port);

	event_dispatch();

	return 0;

}
Esempio n. 8
0
static void et_init(void) {
	event_init();
	struct httpd_cfg httpd_config;
	httpd_config.listen = "0.0.0.0";
	httpd_config.port = 2688;
	httpd_config.timeout = 60;

	httpd = evhttp_start(httpd_config.listen, httpd_config.port);
	if (httpd == NULL) {
		fprintf(stderr, "\nUnable to listen on %s:%d\n\n", httpd_config.listen,
				httpd_config.port);
		kill(0, SIGTERM);
		exit(1);
	}
	evhttp_set_timeout(httpd, httpd_config.timeout);

	/* Set a callback for all other requests. */
	evhttp_set_gencb(httpd, httpd_handler, NULL);
}
Esempio n. 9
0
static void
http_highport_test(void)
{
	int i = -1;
	struct evhttp *myhttp = NULL;
 
	fprintf(stdout, "Testing HTTP Server with high port: ");

	/* Try a few different ports */
	for (i = 0; i < 50; ++i) {
		myhttp = evhttp_start("127.0.0.1", 65535 - i);
		if (myhttp != NULL) {
			fprintf(stdout, "OK\n");
			evhttp_free(myhttp);
			return;
		}
	}

	fprintf(stdout, "FAILED\n");
	exit(1);
}
Esempio n. 10
0
static struct evhttp *
http_setup(short *pport)
{
	int i;
	struct evhttp *myhttp;
	short port = -1;

	/* Try a few different ports */
	for (i = 0; i < 50; ++i) {
		myhttp = evhttp_start("127.0.0.1", 8080 + i);
		if (myhttp != NULL) {
			port = 8080 + i;
			break;
		}
	}

	if (port == -1)
		event_errx(1, "Could not start web server");

	*pport = port;
	return (myhttp);
}
Esempio n. 11
0
void
signal_handler(int sig) {
	switch(sig) {
		
		case SIGHUP:
			ini_parse(&Ctx);
			tolog(&Ctx, LOG_ERROR, "server restarted ");
			evhttp_free(httpd);
			httpd = evhttp_start(Ctx.bind, Ctx.port);
			evhttp_set_gencb(httpd, http_handler, NULL);
			event_dispatch();

			break;
		case SIGTERM:
		case SIGINT:
			event_loopbreak();
			break;
        default:
            //syslog(LOG_WARNING, "Unhandled signal (%d) %s", strsignal(sig));
            break;
    }
}
Esempio n. 12
0
int
main(int argc, char **argv)
{
        struct evhttp *httpd;

        event_init();
        httpd = evhttp_start("0.0.0.0", 8080);

        /* Set a callback for requests to "/". */
        evhttp_set_cb(httpd, "/", root_handler, NULL);

        /* Set a callback for all other requests. */
        evhttp_set_gencb(httpd, generic_handler, NULL);

        event_dispatch();

        /* Not reached in this code as it is now. */

        evhttp_free(httpd);

        return 0;
}
Esempio n. 13
0
int main(int argc, char **argv)
{
    init_app(argc, argv, "osd");

    event_init();

    char *hdd_cfg = cfg_getstr("HDD_CONF_FILENAME", "etc/hdd.conf");
    hdd_init(hdd_cfg);

    char *self_host = cfg_getstr("OSD2CLIENT_LISTEN_HOST", "*");
    int self_port = cfg_getint32("OSD2CLIENT_LISTEN_PORT", 9527);
    rpc_client_setup(self_host, self_port, MACHINE_OSD);

    struct evhttp *httpd;

    char *listen_host = cfg_getstr("OSD2CLIENT_LISTEN_HOST", "*");
    int port = cfg_getint32("OSD2CLIENT_LISTEN_PORT", 9527);

    httpd = evhttp_start(listen_host, port);
    if (httpd == NULL) {
        logging(LOG_ERROR, "start server error %m");
        exit(1);
    } else {
        printf("Start osd at %s:%d\n", listen_host, port);
    }
    evhttp_set_cb(httpd, "/shutdown", shutdown_handler, NULL);
    evhttp_set_gencb(httpd, gen_handler, NULL);


    struct timeval five_seconds = {2,0};
    struct event *update_clustermap_event= event_new(NULL, -1, EV_PERSIST, update_clustermap_from_cmgr_on_timer_cb, NULL);
    event_add(update_clustermap_event, &five_seconds);

    event_dispatch();

    evhttp_free(httpd);
    return 0;
}
Esempio n. 14
0
int main(int argc, char **argv)
{
	int c;
	/* 默认参数设置 */
	char *httpsqs_settings_listen = "0.0.0.0";
	int httpsqs_settings_port = 2789;
    char *redis_settings_listen = "127.0.0.1";
    int redis_settings_port = 6379;
	bool httpsqs_settings_daemon = false;
	int httpsqs_settings_timeout = 3; /* 单位:秒 */
	httpsqs_settings_pidfile = "/tmp/httpredisq.pid";

    /* process arguments */
    while ((c = getopt(argc, argv, "l:p:r:o:i:t:dh")) != -1) {
        switch (c) {
        case 'l':
            httpsqs_settings_listen = strdup(optarg);
            break;
        case 'p':
            httpsqs_settings_port = atoi(optarg);
            break;
        case 'r':
            redis_settings_listen = strdup(optarg);
            break;
        case 'o':
            redis_settings_port = atoi(optarg);
            break;
        case 'i':
            httpsqs_settings_pidfile = strdup(optarg);
            break;			
        case 't':
            httpsqs_settings_timeout = atoi(optarg);
            break;
        case 'd':
            httpsqs_settings_daemon = true;
            break;
		case 'h':
        default:
            show_help();
            return 1;
        }
    }

    redis_client = redisConnect(redis_settings_listen, redis_settings_port);
    if (redis_client -> err) {
        fprintf(stderr, "Connect redis server error:%s\n", redis_client->errstr);
        return 1;
    }
    
	/* 如果加了-d参数,以守护进程运行 */
	if (httpsqs_settings_daemon == true){
        pid_t pid;

        /* Fork off the parent process */       
        pid = fork();
        if (pid < 0) {
                exit(EXIT_FAILURE);
        }
        /* If we got a good PID, then
           we can exit the parent process. */
        if (pid > 0) {
                exit(EXIT_SUCCESS);
        }
	}
	
	/* 将进程号写入PID文件 */
	FILE *fp_pidfile;
	fp_pidfile = fopen(httpsqs_settings_pidfile, "w");
	fprintf(fp_pidfile, "%d\n", getpid());
	fclose(fp_pidfile);
	
	/* 忽略Broken Pipe信号 */
	signal(SIGPIPE, SIG_IGN);
	
	/* 处理kill信号 */
	signal (SIGINT, kill_signal);
	signal (SIGKILL, kill_signal);
	signal (SIGQUIT, kill_signal);
	signal (SIGTERM, kill_signal);
	signal (SIGHUP, kill_signal);
	
	/* 请求处理部分 */
    struct evhttp *httpd;

    event_init();
    httpd = evhttp_start(httpsqs_settings_listen, httpsqs_settings_port);
	if (httpd == NULL) {
		fprintf(stderr, "Error: Unable to listen on %s:%d\n\n", httpsqs_settings_listen, httpsqs_settings_port);		
		exit(1);		
	}
	evhttp_set_timeout(httpd, httpsqs_settings_timeout);

    /* Set a callback for requests to "/specific". */
    /* evhttp_set_cb(httpd, "/select", select_handler, NULL); */

    /* Set a callback for all other requests. */
    evhttp_set_gencb(httpd, httpsqs_handler, NULL);

    event_dispatch();

    /* Not reached in this code as it is now. */
    evhttp_free(httpd);

    return 0;
}
Esempio n. 15
0
int main(int argc, char **argv)
{
	int c;
	/* 默认参数设置 */
	char *httpcws_settings_listen = "0.0.0.0";
	int httpcws_settings_port = 1985;
	char *httpcws_settings_datapath = NULL; /*中文词典数据库路径 */
	bool httpcws_settings_daemon = false;
	int httpcws_settings_timeout = 120; /* 单位:秒 */

    /* process arguments */
    while ((c = getopt(argc, argv, "l:p:x:t:dh")) != -1) {
        switch (c) {
        case 'l':
            httpcws_settings_listen = strdup(optarg);
            break;
        case 'p':
            httpcws_settings_port = atoi(optarg);
            break;
        case 'x':
            httpcws_settings_datapath = strdup(optarg); /* 词库文件存储路径 */
            break;
        case 't':
            httpcws_settings_timeout = atoi(optarg);
            break;			
        case 'd':
            httpcws_settings_daemon = true;
            break;
		case 'h':			
        default:
            show_help();
            return 1;
        }
    }
	
	/* 判断是否加了必填参数 -x */
	if (httpcws_settings_datapath == NULL) {
		show_help();
		fprintf(stderr, "Attention: Please use the indispensable argument: -x <path>\n\n");		
		exit(1);
	}

	/* 初始化分词组件 */
	if(!ICTCLAS_Init(httpcws_settings_datapath))
	{
		printf("%s\n", httpcws_settings_datapath);
		fprintf(stderr, "ERROR: Count not open the Chinese dictionary!\n\n");		
		exit(1);
	}
	ICTCLAS_SetPOSmap(ICT_POS_MAP_SECOND);

	fprintf(stderr, "Loading Chinese dictionary 'httpcws_dict.txt' into memory, please waitting ......\n");
	char *httpcws_settings_dataname = (char *)malloc(1024);
	memset (httpcws_settings_dataname, '\0', 1024);
	sprintf(httpcws_settings_dataname, "%s/httpcws_dict.txt", httpcws_settings_datapath);
	int nCount = ICTCLAS_ImportUserDict(httpcws_settings_dataname);
	ICTCLAS_SaveTheUsrDic();
	free(httpcws_settings_dataname);
	printf("OK! %d words has loaded into memory.\n\n", nCount);
	printf("HTTPCWS Server running on %s:%d\n", httpcws_settings_listen, httpcws_settings_port);

	/* 如果加了-d参数,以守护进程运行 */
	if (httpcws_settings_daemon == true){
        pid_t pid;

        /* Fork off the parent process */       
        pid = fork();
        if (pid < 0) {
                exit(EXIT_FAILURE);
        }
        /* If we got a good PID, then
           we can exit the parent process. */
        if (pid > 0) {
                exit(EXIT_SUCCESS);
        }
	}
	
	/* 请求处理部分 */
	struct evhttp *httpd;

	event_init();
	httpd = evhttp_start(httpcws_settings_listen, httpcws_settings_port);
	evhttp_set_timeout(httpd, httpcws_settings_timeout);

	/* Set a callback for all other requests. */
	evhttp_set_gencb(httpd, httpcws_handler, NULL);

	event_dispatch();

	/* Not reached in this code as it is now. */
	evhttp_free(httpd);

    return 0;
}
Esempio n. 16
0
int main(int argc, char **argv){
	unsigned int i;
	char * ptr;

	unsigned int numthreads;

	global_data * global = new global_data;

	global->stats.starttime = get_now();

//2 queues
	global->request  = new tqueue<request_t>();
	global->response = new tqueue<request_t>();

//thread stuff
	pthread_t thread[MAX_THREADS];
	thread_data_t threaddata[MAX_THREADS];

//http server stuff
	struct evhttp *http;
	struct event updateEvent;


//notification fds
	int fds[2];

	srand(time(NULL));

	//defaults
	char port_def[] = "80";
	char hostname_def[] = "0.0.0.0";
	char threads_def[] = "3";
	char static_source_def[] = "pentagoo/";

	//Argument Pointers
	char *port_arg = port_def;
	char *hostname_arg = hostname_def;
	char *threads_arg = threads_def;
	char *static_source = static_source_def;


//Parse command line options
	for (i = 1; i < (unsigned int)argc; i++) {
		ptr = argv[i];
		if(strcmp(ptr, "--help") == 0){
			printf("Usage:\n"
				"\t--help        Show this help\n"
				"\t-l            Location for the web frontend [%s]\n"
				"\t-p            Port Number [%s]\n"
				"\t-h            Hostname [%s]\n"
				"\t-t            Number of threads [%s]\n\n",
				static_source_def, port_def, hostname_def, threads_def);
			exit(255);
		}else if (strcmp(ptr, "-p") == 0)
			port_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-h") == 0)
			hostname_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-t") == 0)
			threads_arg = ptr = argv[++i];
		else if (strcmp(ptr, "-l") == 0)
			static_source = ptr = argv[++i];
	}


	global->static_source = static_source;

	numthreads = atoi(threads_arg);
	if(numthreads < 1)
		numthreads = 1;

	if(numthreads > MAX_THREADS){
		printf("Invalid number of threads '%s', setting to max threads %i\n", threads_arg, MAX_THREADS);
		numthreads = MAX_THREADS;
	}

//initialize update notification pipe
	socketpair(AF_UNIX, SOCK_STREAM, 0, fds);

	global->pushfd = fds[0];
	global->popfd = fds[1];


	printf("Starting %u computation threads\n", numthreads);

	for(i = 0; i < numthreads; i++){
		threaddata[i].threadid = i;
		threaddata[i].state = 1;
		threaddata[i].global = global;
		
		pthread_create(&thread[i], NULL, (void* (*)(void*)) requestRunner, (void*) &threaddata[i]);
	}


//init the event lib
	event_init();


	printf("Listening on %s:%s\n", hostname_arg, port_arg);

//start the http server
	http = evhttp_start(hostname_arg, atoi(port_arg));
	if(http == NULL) {
		printf("Couldn't start server on %s:%s\n", hostname_arg, port_arg);
		return 1;
	}


//Register a callback for requests
	evhttp_set_gencb(http, handle_http_static, global); //the generic catch all callback, used to serve static files
	evhttp_set_cb(http, "/ai",              handle_request_ai,       global); //my nice url
	evhttp_set_cb(http, "/pentagoo_ai.php", handle_request_ai,       global); //hijack the pentagoo url

	evhttp_set_cb(http, "/stats",    handle_request_stats,    global);

	event_set(& updateEvent, global->popfd, EV_READ|EV_PERSIST, handle_queue_response, global);
	event_add(& updateEvent, 0);


	printf("Starting event loop\n");

	event_dispatch();


	printf("Exiting\n");

	global->request->nonblock();
	for(i = 0; i < numthreads; i++)
		pthread_join(thread[i], NULL);

	return 0;
}
Esempio n. 17
0
int main(int argc, char **argv)
{
    settings_init();
    
    struct rlimit rlim;
    int c;
        
    while (-1 != (c = getopt(argc, argv,
        "c:"  /* max simultaneous connections */
        "p:"  /* TCP port number to listen on */
        "l:"  /* interface to listen on, default is INADDR_ANY */
        "m:"  /* Memcached servers */
        "v"   /* verbose */
        "h"
        ))) {
        switch (c) {
        case 'c':
            settings.maxconns = atoi(optarg);
            break;
        case 'p':
            settings.port = atoi(optarg);
            break;
        case 'l':
            settings.inter = optarg;
            break;
        case 'm':
            settings.memcached_pool = optarg;
            break;
        case 'h':
            usage();
            exit(EXIT_SUCCESS);
        case 'v':
            settings.verbose++;
            break;
        default:
            fprintf(stderr, "Illegal argument \"%c\"\n", c);
            return 1;
        }
    }

    if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
        fprintf(stderr, "failed to getrlimit number of files\n");
        exit(EX_OSERR);
    } else {
        int maxfiles = settings.maxconns;
        if (rlim.rlim_cur < maxfiles)
            rlim.rlim_cur = maxfiles + 3;
        if (rlim.rlim_max < rlim.rlim_cur)
            rlim.rlim_max = rlim.rlim_cur;
        if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
            fprintf(stderr, "failed to set rlimit for open files. Try running as root or requesting smaller maxconns value.\n");
            exit(EX_OSERR);
        }
    }
    
    if (settings.verbose > 0)
        fprintf(stderr, "maxconns set to: %d\n", settings.maxconns);
    
    init_memcached();

    pthread_attr_t tattr;
    pthread_t helper;
    pthread_create(&helper, NULL, cnode_run, NULL);
    
    int i;
    for(i=0;i<=MAXUSERS;i++) slots[i]=i;
    
    struct evhttp *httpd;
    event_init();
    httpd = evhttp_start(settings.inter, settings.port);
    
    if (settings.verbose > 0)
        fprintf(stderr, "server listening on %s:%d\n", settings.inter, settings.port);
                
    evhttp_set_gencb(httpd, request_handler, NULL);
    event_dispatch();
    evhttp_free(httpd);
    memcached_free(memc);
    return 0;
}
Esempio n. 18
0
void av_startup()
{
  if( !_av.clock_get )
		{
		puts( "[Avon] Error: clock callbacks must be installed before startup. Quit." );
		exit(-1);
	 }

  if( !_av.pva_set ||
		!_av.pva_get ||
		!_av.geom_set || 
		!_av.geom_get )
	 {
		puts( "[Avon] Error: generic callbacks must be installed before startup. Quit." );
		exit(-1);
	 }
  
	// set up server root for real files
	if( chdir( _av.rootdir ) )
		{
			printf( "failed to set %s as working directory. Quit.\n", _av.rootdir );
			exit(-1);
		}

	char* cwd = getcwd(NULL,0);
	
  if( _av.verbose )
    {
      printf( "[%s] %s %s hosting %s %s at http://%s root %s\n", 
							_package, 
							_package,
							_version,
							_av.backend_name, // implemented by the simulator
							_av.backend_version,
							_av.hostportname,
							cwd );
    }
	
	free(cwd);
	
  // Set up the HTTP server
  event_init();
  
  if( _av.verbose )
    {
      printf("[%s] Starting HTTP server...", _package );
      fflush(stdout);
    }
	
  _av.eh = evhttp_start( _av.hostname, _av.port);
  assert(_av.eh);
	
	// set specific callbacks here (e.g. sim things, favicon, homepage, etc );

	//evhttp_set_cb( _av.eh, FAVICONFILE, FaviconCallback, (void*)this );

	// install all the sim handlers
	//evhttp_set_cb( _av.eh, "/sim/clock", (evhttp_cb_t)SimClockCb, (void*)this );
	
	evhttp_set_cb( _av.eh, "/sim/tree", (evhttp_cb_t)handle_tree, NULL );

	evhttp_set_cb( _av.eh, "/", (evhttp_cb_t)handle_index, NULL );
	evhttp_set_cb( _av.eh, "/index.html", (evhttp_cb_t)handle_index, NULL );

  //evhttp_set_gencb( _av.eh, &WebSim::EventCallback, (void*)this );
  
  if( _av.verbose )
    {
      puts( " done." );
    }
}
Esempio n. 19
0
int main(int argc, char *argv[], char *envp[]) {

	int c;
	char *synchttp_settings_listen = "0.0.0.0";
	int synchttp_settings_port = 2688;
	char *synchttp_settings_datapath = NULL;
	bool synchttp_settings_daemon = false;
	int synchttp_settings_timeout = 60; /* 单位:秒 */
	synchttp_settings_syncinterval = 5; /* 单位:秒 */
	int synchttp_settings_cachenonleaf = 1024; /* 缓存非叶子节点数。单位:条 */
	int synchttp_settings_cacheleaf = 2048; /* 缓存叶子节点数。叶子节点缓存数为非叶子节点数的两倍。单位:条 */
	int synchttp_settings_mappedmemory = 104857600; /* 单位:字节 */
	synchttp_settings_pidfile = "/tmp/synchttp.pid";
	synchttp_settings_auth = NULL; /* 验证密码 */

	/* 启动选项 */
	while ((c = getopt(argc, argv, "l:p:x:t:s:c:m:i:a:w:dh")) != -1) {
		switch (c) {
		case 'l':
			synchttp_settings_listen = strdup(optarg);
			break;
		case 'p':
			synchttp_settings_port = atoi(optarg);
			break;
		case 'x':
			synchttp_settings_datapath = strdup(optarg); /* synchttp数据库文件存放路径 */
			if (access(synchttp_settings_datapath, W_OK) != 0) { /* 如果目录不可写 */
				if (access(synchttp_settings_datapath, R_OK) == 0) { /* 如果目录可读 */
					chmod(synchttp_settings_datapath, S_IWOTH); /* 设置其他用户具可写入权限 */
				} else { /* 如果不存在该目录,则创建 */
					create_multilayer_dir(synchttp_settings_datapath);
				}
				if (access(synchttp_settings_datapath, W_OK) != 0) { /* 如果目录不可写 */
					fprintf(stderr, "synchttp database directory not writable\n");
				}
			}
			break;
		case 't':
			synchttp_settings_timeout = atoi(optarg);
			break;
		case 's':
			synchttp_settings_syncinterval = atoi(optarg);
			break;
		case 'c':
			synchttp_settings_cachenonleaf = atoi(optarg);
			synchttp_settings_cacheleaf = synchttp_settings_cachenonleaf * 2;
			break;
		case 'm':
			synchttp_settings_mappedmemory = atoi(optarg) * 1024 * 1024; /* 单位:M */
			break;
		case 'i':
			synchttp_settings_pidfile = strdup(optarg);
			break;
		case 'a':
			synchttp_settings_auth = strdup(optarg);
			break;
		case 'd':
			synchttp_settings_daemon = true;
			break;
		case 'h':
		default:
			show_help();
			return 1;
		}
	}

	/* 判断是否加了必填参数 -x */
	if (synchttp_settings_datapath == NULL) {
		show_help();
		fprintf(stderr, "Attention: Please use the indispensable argument: -x <path>\n\n");
		exit(1);
	}

	/*curl初始化全局信息*/
	if ((curl_global_init(CURL_GLOBAL_ALL)) != CURLE_OK) {
		fprintf(stderr, "Curl global init fail.\n");
		exit(1);
	}

	/* 数据表路径 */
	int synchttp_settings_dataname_len = 1024;
	char *synchttp_settings_dataname = (char *) tccalloc(1, synchttp_settings_dataname_len);
	sprintf(synchttp_settings_dataname, "%s/synchttp.db", synchttp_settings_datapath);

	/* 打开数据表 */
	synchttp_db_tcbdb = tcbdbnew();
	tcbdbsetmutex(synchttp_db_tcbdb); /* 开启线程互斥锁 */
	tcbdbtune(synchttp_db_tcbdb, 1024, 2048, 50000000, 8, 10, BDBTLARGE);
	tcbdbsetcache(synchttp_db_tcbdb, synchttp_settings_cacheleaf,
			synchttp_settings_cachenonleaf);
	tcbdbsetxmsiz(synchttp_db_tcbdb, synchttp_settings_mappedmemory); /* 内存缓存大小 */

	/* 判断表是否能打开 */
	if (!tcbdbopen(synchttp_db_tcbdb, synchttp_settings_dataname, BDBOWRITER | BDBOCREAT)) {
		fprintf(stderr, "Attention: Unable to open the database.\n\n");
		exit(1);
	}
	/* 释放变量所占内存 */
	free(synchttp_settings_dataname);

	/* 如果加了-d参数,以守护进程运行 */
	if (synchttp_settings_daemon == true) {
		pid_t pid;

		/* Fork off the parent process */
		pid = fork();
		if (pid < 0) {
			exit(EXIT_FAILURE);
		}
		/* If we got a good PID, then
		 we can exit the parent process. */
		if (pid > 0) {
			exit(EXIT_SUCCESS);
		}
	}

	/* 将进程号写入PID文件 */
	FILE *fp_pidfile;
	fp_pidfile = fopen(synchttp_settings_pidfile, "w");
	fprintf(fp_pidfile, "%d\n", getpid());
	fclose(fp_pidfile);

	/* 派生synchttp子进程(工作进程) */
	pid_t synchttp_worker_pid_wait;
	pid_t synchttp_worker_pid = fork();
	/* 如果派生进程失败,则退出程序 */
	if (synchttp_worker_pid < 0) {
		fprintf(stderr, "Error: %s:%d\n", __FILE__, __LINE__);
		exit(EXIT_FAILURE);
	}

	/* synchttp父进程内容 */
	if (synchttp_worker_pid > 0) {
		/* 处理父进程接收到的kill信号 */

		/* 忽略Broken Pipe信号 */
		signal(SIGPIPE, SIG_IGN);

		/* 处理kill信号 */
		signal(SIGINT, kill_signal_master);
		signal(SIGKILL, kill_signal_master);
		signal(SIGQUIT, kill_signal_master);
		signal(SIGTERM, kill_signal_master);
		signal(SIGHUP, kill_signal_master);

		/* 处理段错误信号 */
		signal(SIGSEGV, kill_signal_master);

		/* 如果子进程终止,则重新派生新的子进程 */
		while (1) {
			synchttp_worker_pid_wait = wait(NULL);
			if (synchttp_worker_pid_wait < 0) {
				continue;
			}
			usleep(100000);
			synchttp_worker_pid = fork();
			if (synchttp_worker_pid == 0) {
				break;
			}
		}
	}

	/*****************************************子进程处理************************************/
	/* 忽略Broken Pipe信号 */
	signal(SIGPIPE, SIG_IGN);

	/* 处理kill信号 */
	signal(SIGINT, kill_signal_worker);
	signal(SIGKILL, kill_signal_worker);
	signal(SIGQUIT, kill_signal_worker);
	signal(SIGTERM, kill_signal_worker);
	signal(SIGHUP, kill_signal_worker);

	/* 处理段错误信号 */
	signal(SIGSEGV, kill_signal_worker);

	/*创建消息队列监听进程*/
	pthread_t synchttp_dispatch_tid;
	pthread_create(&synchttp_dispatch_tid, NULL, (void *) synchttp_dispatch, NULL);

	/* 创建定时同步线程,定时将内存中的内容写入磁盘 */
	pthread_t synchttp_worker_tid;
	pthread_create(&synchttp_worker_tid, NULL, (void *) synchttp_worker, NULL);

	/* 外部请求处理部分 */
	struct evhttp *synchttpd;
	event_init();
	synchttpd = evhttp_start(synchttp_settings_listen, synchttp_settings_port);
	if (synchttpd == NULL) {
		fprintf(stderr, "Error: Unable to listen on %s:%d\n\n", synchttp_settings_listen, synchttp_settings_port);
		kill(0, SIGTERM);
		exit(1);
	}
	evhttp_set_timeout(synchttpd, synchttp_settings_timeout);
	evhttp_set_gencb(synchttpd, synchttp_handler, NULL);
	event_dispatch();
	evhttp_free(synchttpd);
}
Esempio n. 20
0
int main(int argc, char **argv)
{
	//自定义信号处理函数
#ifndef __WIN32
	signal(SIGHUP, signal_handler);
	signal(SIGQUIT, signal_handler);
#endif
	signal(SIGTERM, signal_handler);
	signal(SIGINT, signal_handler);

	//默认参数
	char *event_option_listen = "127.0.0.1";
	int event_option_port = 8706;
	int event_option_daemon = 0;
	int event_option_timeout = 60;
	int event_option_socket = 0;

	//获取参数
	int c;
	while ((c = getopt(argc, argv, "l:p:dst:vh")) != -1) {
		switch (c) {
			case 'l' :
				event_option_listen = optarg;
				break;
			case 'p' :
				event_option_port = atoi(optarg);
				break;
			case 'd' :
				event_option_daemon = 1;
				break;
			case 's' :
				event_option_socket = 1;
				break;
			case 't' :
				event_option_timeout = atoi(optarg);
				break;
			case 'v' :
				show_version();
				exit(EXIT_SUCCESS);
			case 'h' :
			default :
				show_help();
				exit(EXIT_SUCCESS);
		}
	}

	//判断是否设置了-d,以daemon运行
	if (event_option_daemon) {
		pid_t pid = 0;
#ifndef __WIN32
		pid = fork();
#endif
		if (pid < 0) {
			perror("Failed to fork\n");
			exit(EXIT_FAILURE);
		}
		if (pid > 0) {
			//生成子进程成功,退出父进程
			exit(EXIT_SUCCESS);
		}
	}

	//初始化event API
    event_init();

	//判断是否设置了-s,以socket运行
	if (event_option_socket) {
		int socketlisten;
		struct sockaddr_in addresslisten;
		struct event accept_event;

#ifdef __WIN32
		unsigned short ver;
		WSADATA wsaData;
		ver = MAKEWORD(1, 1);
		WSAStartup(ver, &wsaData);
#endif
		socketlisten = socket(AF_INET, SOCK_STREAM, 0);
		if (socketlisten < 0) {
			fprintf(stderr, "Failed to create listen socket\n");
			exit(1);
		}

		memset(&addresslisten, 0, sizeof(addresslisten));
		addresslisten.sin_family = AF_INET;
		addresslisten.sin_addr.s_addr = inet_addr(event_option_listen);
		addresslisten.sin_port = htons(event_option_port);
		if (bind(socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0) {
			fprintf(stderr, "Failed to bind socket %s:%d\n", event_option_listen, event_option_port);
			exit(1);
		}

		if (listen(socketlisten, 5) < 0) {
			fprintf(stderr, "Failed to listen to socket\n");
			exit(1);
		}
#ifdef __WIN32
		char reuse = 1;
#else
		int reuse = 1;
#endif
		setsockopt(socketlisten, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
		set_nonblock(socketlisten);

		event_set(&accept_event, socketlisten, EV_READ|EV_PERSIST, on_accept, NULL);
		event_add(&accept_event, NULL);
		event_dispatch();

		close(socketlisten);
#ifdef __WIN32
		WSACleanup();
#endif
		return 0;
	}

    // 绑定IP和端口
#ifdef __WIN32
	unsigned short ver;
	WSADATA wsaData;
	ver = MAKEWORD(1, 1);
	WSAStartup(ver, &wsaData);
#endif
    struct evhttp *httpd;
	httpd = evhttp_start(event_option_listen, event_option_port);

    if (httpd == NULL) {
        fprintf(stderr, "Failed to listen on %s:%d\n", event_option_listen, event_option_port);
        exit(1);
    }

    // 设置请求超时时间
    evhttp_set_timeout(httpd, event_option_timeout);

    // 设置请求的处理函数
    evhttp_set_gencb(httpd, http_handler, NULL);
    event_dispatch();
    evhttp_free(httpd);
#ifdef __WIN32
	WSACleanup();
#endif

    return 0;
}