// Initializes TCP and LibEvent, then listens for connections on port // and calls accept_cb when they occur. Terminates cleanly on SIGINT. // Returns 0 on clean shutdown; otherwise nonzero int InitAndListenLoop(int port, evconnlistener_cb accept_cb, struct telex_conf *conf) { #ifdef WIN32 WSADATA WSAData; WSAStartup(0x101, &WSAData); #endif struct event_base *base; base = event_base_new(); if (!base) { LogFatal("listener", "Could not initialize libevent"); return 1; } conf->dns_base = evdns_base_new(base, 1); if (!conf->dns_base) { LogFatal("listener", "Could not initialize dns"); return 1; } struct evconnlistener *listener; listener = listener_init_local(base, port, accept_cb, conf, NULL); if (!listener) { LogFatal("listener", "Could not create listener"); return 1; } struct event *signal_event; signal_event = evsignal_new(base, SIGINT, sigint_cb, (void *)base); if (!signal_event || event_add(signal_event, NULL)<0) { LogFatal("listener", "Could not create/add signal event"); return 1; } // handle events ... LogTrace("listener", "Starting dispatch"); event_base_dispatch(base); evconnlistener_free(listener); event_free(signal_event); event_base_free(base); LogInfo("listener", "Shutdown complete"); return 0; }
/* Thread: main */ void filescanner_deinit(void) { int ret; #ifdef USE_EVENTFD ret = eventfd_write(exit_efd, 1); if (ret < 0) { DPRINTF(E_FATAL, L_SCAN, "Could not send exit event: %s\n", strerror(errno)); return; } #else int dummy = 42; ret = write(exit_pipe[1], &dummy, sizeof(dummy)); if (ret != sizeof(dummy)) { DPRINTF(E_FATAL, L_SCAN, "Could not write to exit fd: %s\n", strerror(errno)); return; } #endif scan_exit = 1; ret = pthread_join(tid_scan, NULL); if (ret != 0) { DPRINTF(E_FATAL, L_SCAN, "Could not join filescanner thread: %s\n", strerror(errno)); return; } inofd_event_unset(); #ifdef USE_EVENTFD close(exit_efd); #else close(exit_pipe[0]); close(exit_pipe[1]); #endif event_base_free(evbase_scan); }
int main() { evbase_t *evbase = event_base_new(); evhtp_t *htp = evhtp_new(evbase, NULL); fprintf(stdout, "Welcome to CAvatar.\n"); // A place for our images mkdir(imgfolder, 0700); // A few static routes evhtp_set_cb(htp, "/", route_index, NULL); evhtp_set_cb(htp, "/favicon.ico", route_favicon, NULL); // Metas evhtp_set_regex_cb(htp, "[\\/](meta)[\\/]([0-9a-fA-F]{32})", route_meta, NULL); // Images evhtp_set_regex_cb(htp, "[\\/](avatar)[\\/]([0-9a-fA-F]{32})", route_image, NULL); evhtp_set_regex_cb(htp, "[\\/]([0-9a-fA-F]{32})", route_image, NULL); // 404 routes evhtp_set_regex_cb(htp, "[\\/](.{1,})", route_generic, NULL); evhtp_set_gencb(htp, route_generic, NULL); // libevhtp has a cool wrapper for pthreads evhtp_use_threads(htp, NULL, threads, NULL); // aaaand bind a socket.. if (evhtp_bind_socket(htp, "0.0.0.0", port, 1024) < 0) { fprintf(stderr, "Could not bind to socket %d: %s\n", port, strerror(errno)); exit(-1); } fprintf(stdout, "Binded to socket %d\n", port); // and listen! event_base_loop(evbase, 0); // free stuff after event loop evhtp_unbind_socket(htp); evhtp_free(htp); event_base_free(evbase); //MagickWandTerminus(); return 0; }
static void thread_deferred_cb_skew(void *arg) { struct timeval tv_timer = {1, 0}; struct event_base *base = NULL; struct event_config *cfg = NULL; struct timeval elapsed; int elapsed_usec; int i; cfg = event_config_new(); tt_assert(cfg); event_config_set_max_dispatch_interval(cfg, NULL, 16, 0); base = event_base_new_with_config(cfg); tt_assert(base); for (i = 0; i < QUEUE_THREAD_COUNT; ++i) deferred_data[i].queue = base; evutil_gettimeofday(&timer_start, NULL); event_base_once(base, -1, EV_TIMEOUT, timer_callback, NULL, &tv_timer); event_base_once(base, -1, EV_TIMEOUT, start_threads_callback, NULL, NULL); event_base_dispatch(base); evutil_timersub(&timer_end, &timer_start, &elapsed); TT_BLATHER(("callback count, %u", callback_count)); elapsed_usec = (unsigned)(elapsed.tv_sec*1000000 + elapsed.tv_usec); TT_BLATHER(("elapsed time, %u usec", elapsed_usec)); /* XXX be more intelligent here. just make sure skew is * within .4 seconds for now. */ tt_assert(elapsed_usec >= 600000 && elapsed_usec <= 1400000); end: for (i = 0; i < QUEUE_THREAD_COUNT; ++i) THREAD_JOIN(load_threads[i]); if (base) event_base_free(base); if (cfg) event_config_free(cfg); }
int main(int argc, char **argv) { struct event_base *base; struct evconnlistener *listener; struct event *signal_event; struct sockaddr_in sin; base = event_init(); if (!base) { fprintf(stderr, "Could not initialize libevent!\n"); return 1; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(PORT); listener = evconnlistener_new_bind(base, listener_cb, (void *)base, LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr*)&sin, sizeof(sin)); if (!listener) { fprintf(stderr, "Could not create a listener!\n"); return 1; } signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base); if (!signal_event || event_add(signal_event, NULL)<0) { fprintf(stderr, "Could not create/add a signal event!\n"); return 1; } event_base_dispatch(base); evconnlistener_free(listener); event_free(signal_event); event_base_free(base); printf("done\n"); return 0; }
void worker_deinit(void) { int ret; g_initialized = 0; commands_base_destroy(cmdbase); ret = pthread_join(tid_worker, NULL); if (ret != 0) { DPRINTF(E_FATAL, L_MAIN, "Could not join worker thread: %s\n", strerror(errno)); return; } // Free event base (should free events too) event_base_free(evbase_worker); }
void CTcpServer::start() { eventPool_.setThreadNum(2); eventPool_.start(); struct sockaddr_in sin; memset(&sin, 0, sizeof(sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = htons(9995); struct event_base* base = event_base_new(); listener_ = evconnlistener_new_bind(base, listenCallback, this, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, (sockaddr*)&sin, sizeof(sin)); event_base_dispatch(base); evconnlistener_free(listener_); event_base_free(base); }
WorkerThread::~WorkerThread() { if(notfiy_recv_fd_!=-1) close(notfiy_recv_fd_); if(notfiy_send_fd_!=-1) close(notfiy_send_fd_); if(pthread_event_base_!=NULL) event_base_free(pthread_event_base_); if(pnotify_event_!=NULL) event_free(pnotify_event_); if(ptimeout_event_) event_free(ptimeout_event_); // for(auto pos=map_tcp_conns_.begin();pos!=map_tcp_conns_.end();++pos) // delete pos->second; // for(auto pos=map_udp_conns_.begin();pos!=map_udp_conns_.end();++pos) // delete pos->second; }
TcpListener::~TcpListener() { if (clients_.size() > 0) { clients_.clear(); } if (listener_) { evconnlistener_free(listener_); listener_ = nullptr; } if (base_) { event_base_free(base_); base_ = nullptr; } }
static void closeAndFreeClient(client_t *client) { if (client != NULL) { closeClient(client); if (client->buf_ev != NULL) { bufferevent_free(client->buf_ev); client->buf_ev = NULL; } if (client->evbase != NULL) { event_base_free(client->evbase); client->evbase = NULL; } if (client->output_buffer != NULL) { evbuffer_free(client->output_buffer); client->output_buffer = NULL; } free(client); } }
int main(){ //делаем соект static evutil_socket_t master_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(-1==master_socket) std::cout << "socket():\n"<<errno<<std::endl; else{ //делаем структуру struct sockaddr_in sa; sa.sin_family=AF_INET; sa.sin_port=htons(12345); sa.sin_addr.s_addr=htonl(INADDR_ANY); //биндим if(bind(master_socket,(sockaddr*)&sa,sizeof(sa))==-1) std::cout << "bind:\n"<<errno<<std::endl; else if(listen(master_socket,SOMAXCONN)==-1) std::cout << "listen:\n"<<errno<<std::endl; else{ //повторное использование мастер сокета int optval = 1; setsockopt(master_socket,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(optval)); //не блокирующий set_non_block(master_socket); //делаем ядро struct event_base * base=event_base_new(); //регистрируем события struct event * evn=event_new(base,master_socket,EV_READ|EV_PERSIST,cb_master,event_self_cbarg()); event_add(evn,NULL); //запускаем цикл event_base_dispatch(base); //очищаем event_base_free(base); event_free(evn); //закрываем shutdown(master_socket,SHUT_RDWR); close(master_socket); } } return 0; }
/** \brief SCConfLogReopenAsyncRedis() Open or re-opens connection to redis for logging. * \param log_ctx Log file context allocated by caller */ static int SCConfLogReopenAsyncRedis(LogFileCtx *log_ctx) { SCLogRedisContext * ctx = log_ctx->redis; const char *redis_server = log_ctx->redis_setup.server; int redis_port = log_ctx->redis_setup.port; /* only try to reconnect once per second */ if (ctx->tried >= time(NULL)) { return -1; } ctx->async = redisAsyncConnect(redis_server, redis_port); if (ctx->ev_base != NULL) { event_base_free(ctx->ev_base); } if (ctx->async == NULL) { SCLogError(SC_ERR_MEM_ALLOC, "Error allocate redis async."); ctx->tried = time(NULL); return -1; } if (ctx->async != NULL && ctx->async->err) { SCLogError(SC_ERR_SOCKET, "Error setting to redis async: [%s].", ctx->async->errstr); ctx->tried = time(NULL); return -1; } ctx->ev_base = event_base_new(); if (ctx->ev_base == NULL) { ctx->tried = time(NULL); redisAsyncFree(ctx->async); ctx->async = NULL; return -1; } redisLibeventAttach(ctx->async, ctx->ev_base); log_ctx->redis = ctx; log_ctx->Close = SCLogFileCloseRedis; return 0; }
int main() { processpool p_pool(DFLNUM); p_pool.set_hook(global_process_fun); p_pool.create_processpool(); int sockfd = my_socket::create_socket_for_server(); struct event_base * base = event_base_new(); assert(NULL != base); struct event * sock_ev = event_new(base, sockfd, EV_READ | EV_PERSIST, accept_cb, (void *)&p_pool); assert(NULL != sock_ev); event_add(sock_ev, NULL); int i = 0; struct event * events[DFLNUM]; for( ; i < DFLNUM; ++i) { ar_in[i].id = i; ar_in[i].p_pro_pool = &p_pool; events[i] = event_new(base, p_pool[i].get_fd(), EV_READ | EV_PERSIST, pipe_cb, (void *)&ar_in[i]); assert(NULL != events[i]); event_add(events[i], NULL); } event_base_dispatch(base); event_free(sock_ev); for(i = 0; i < DFLNUM; ++i) { event_free(events[i]); } event_base_free(base); cout << "server stop" << endl; return 0; }
/** * @author sohu-inc.com * 后端检测线程释放销毁 * @param detect_thread */ void backend_detect_thread_free(backend_detect_thread_t *detect_thread) { gboolean is_thread = FALSE; if (!detect_thread) return; is_thread = (detect_thread->thr != NULL); g_debug("[%s]: will join detect thread if needed.", G_STRLOC); if (detect_thread->thr != NULL) { g_thread_join(detect_thread->thr); detect_thread->thr = NULL; } g_debug("[%s]: deleting the event_base of detect thread", G_STRLOC); if (is_thread && detect_thread->event_base) { event_base_free(detect_thread->event_base); detect_thread->event_base = NULL; } if (detect_thread->backend != NULL) { // 这里应用的是上层传来的指针,不用释放backend指向的内存, // 只是将backend置为NULL即可 detect_thread->backend = NULL; } if (detect_thread->chas) { // 这里应用的是上层传来的指针,不用释放chas指向的内存, // 只是将chas置为NULL即可 detect_thread->chas = NULL; } if (detect_thread->name != NULL) { g_string_free(detect_thread->name, TRUE); detect_thread->name = NULL; } if (detect_thread->task != NULL) { detection_task_free(detect_thread->task); detect_thread->task = NULL; } g_free(detect_thread); }
void lgtd_cleanup(void) { lgtd_lifx_discovery_close(); lgtd_listen_close_all(); lgtd_command_pipe_close_all(); lgtd_client_close_all(); lgtd_lifx_broadcast_close(); lgtd_lifx_gateway_close_all(); lgtd_timer_stop_all(); lgtd_close_signal_handling(); event_base_free(lgtd_ev_base); #if LIBEVENT_VERSION_NUMBER >= 0x02010100 libevent_global_shutdown(); #endif if (lgtd_opts.pidfile) { unlink(lgtd_opts.pidfile); } }
void EvHttpSyncClient::close() { FX_DEBUG("Close client"); if (m_pConn) { evhttp_connection_free(m_pConn); m_pConn = NULL; } if (m_evbase && m_bOwnEventBase) { event_base_loopbreak(m_evbase); event_base_free(m_evbase); } m_evbase = NULL; m_lastState = ST_DISCONNECTED; m_pLastRequest = NULL; }
static char *getUserInput(KonohaContext *kctx, char *buff, const char *cid, const char *host, int port) { struct event_base *base = event_base_new(); struct evhttp *httpd = evhttp_new(base); if(evhttp_bind_socket(httpd, host, port) < 0) { PLATAPI LoggerModule.syslog_i(5/*LOG_NOTICE*/, "{\"Method\": \"DScriptError\", \"CId\": \"%s\", \"Body\": \"couldn't bind socket\"}", cid); exit(1); } UserInput ui = {}; ui.base = base; ui.buff = buff; evhttp_set_gencb(httpd, userInput2Buff, (void *)&ui); event_base_dispatch(base); evhttp_free(httpd); event_base_free(base); return buff; }
/*! * @brief Free any associated resources with the client */ static void sstp_client_free(sstp_client_st *client) { /* Destory the HTTPS stream */ if (client->stream) { sstp_stream_destroy(client->stream); client->stream = NULL; } /* Shutdown the SSL context */ if (client->ssl_ctx) { SSL_CTX_free(client->ssl_ctx); client->ssl_ctx = NULL; } /* Close the PPPD layer */ if (client->pppd) { sstp_pppd_free(client->pppd); client->pppd = NULL; } /* Close the IPC */ if (client->event) { sstp_event_free(client->event); client->event = NULL; } /* Free the route context */ if (client->route_ctx) { sstp_route_done(client->route_ctx); client->route_ctx = NULL; } /* Free the options */ sstp_option_free(&client->option); /* Free the event base */ event_base_free(client->ev_base); }
/** \brief SCLogFileCloseRedis() Closes redis log more * \param log_ctx Log file context allocated by caller */ void SCLogFileCloseRedis(LogFileCtx *log_ctx) { SCLogRedisContext * ctx = log_ctx->redis; if (ctx == NULL) { return; } /* asynchronous */ if (log_ctx->redis_setup.is_async) { #if HAVE_LIBEVENT == 1 if (ctx->async) { if (ctx->connected > 0) { SCLogAsyncRedisSendQuit(ctx); } if (ctx->ev_base != NULL) { event_base_free(ctx->ev_base); ctx->ev_base = NULL; } } #endif } /* synchronous */ if (!log_ctx->redis_setup.is_async) { if (ctx->sync) { redisReply *reply; int i; for (i = 0; i < ctx->batch_count; i++) { redisGetReply(ctx->sync, (void **)&reply); if (reply) { freeReplyObject(reply); } } redisFree(ctx->sync); ctx->sync = NULL; } ctx->tried = 0; ctx->batch_count = 0; } if (ctx != NULL) { SCFree(ctx); } }
void* TcpClient::ConnectThread(void *pParam) { TcpClient *pClient = (TcpClient *)pParam; struct sockaddr_in sin; sin.sin_family = AF_INET; inet_pton(AF_INET, pClient->m_cIPAddr, (void*)&sin.sin_addr); sin.sin_port = htons(pClient->m_nPort); int nCycle = 15; while (pClient->m_bConnecting) { if (nCycle < 15) { nCycle++; Sleep(1000); continue; } Tprintf(L"Connecting\n"); nCycle = 0; struct event_base *base = event_base_new(); assert(base != NULL); #if defined (WIN32) evthread_use_windows_threads(); #else evthread_use_pthreads(); #endif evthread_make_base_notifiable(base); struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE); bufferevent_setcb(bev, read_cb, NULL, event_cb, pClient); bufferevent_enable(bev, EV_READ | EV_WRITE | EV_PERSIST); //连接 if (bufferevent_socket_connect(bev, (SOCKADDR*)&sin, sizeof(SOCKADDR)) < 0) { bufferevent_free(bev); return NULL; } event_base_dispatch(base); event_base_free(base); } return NULL; }
//超时事件测试 void timer_test() { // 初始化 base=event_init(); struct event evTime; // 设置定时事件 evtimer_set(&evTime, onTime, &evTime); struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 0; // 添加定时事件 event_add(&evTime, &tv); //设置为base事件 event_base_set(base, &evTime); // 事件调度循环 event_dispatch(); event_base_free(base); }
int JtEventServer::EventLoop() { //默认存在一个定时器 //////JtEventTimer *Timer = new JtEventTimer(); //////Timer->OnAddToServer(this); pEventPairPipe = new JtEventPairPipe(); pEventPairPipe->AddToServer(this); //jtprintf("[%s]event_base_dispatch before\n", __FUNCTION__); Started(); //int res = event_base_loop(base,EVLOOP_NO_EXIT_ON_EMPTY); int res = event_base_dispatch(base); if(res==0) { jtprintf("[%s]event_base_dispatch out res %d\n", __FUNCTION__, res); } else if(res==-1) { jtprintf("[%s]event_base_dispatch error res %d\n", __FUNCTION__, res); } else if(res==1) { jtprintf("[%s]event_base_dispatch no event res %d\n", __FUNCTION__, res); } else { jtprintf("[%s]event_base_dispatch res %d\n", __FUNCTION__, res); } /////delete Timer; delete pEventPairPipe; pEventPairPipe = NULL; //必须先移除所有的事件,然后再调用event_base_free event_base_free(base); base = NULL; // return 0; }
void server_free(server *s) { int i; /* shutdown worker threads */ for(i=0; i<s->cfg->workers; i++) { worker_free(s->w[i]); } /* free */ event_del(s->signal); event_free(s->signal); event_base_free(s->base); close(s->fd); free(s->w); conf_free(s->cfg); log_free(s->log); free(s); }
int main () { SSL_library_init (); ERR_load_crypto_strings (); SSL_load_error_strings (); OpenSSL_add_all_algorithms(); event_enable_debug_mode (); evbase = event_base_new (); dnsbase = evdns_base_new (evbase, 1); perform_ssl_connection (); event_base_dispatch (evbase); event_base_free (evbase); return 0; }
GuNET_Server_Error_t GuNET_Server_Free(GuNET_Server_t * server) { GuNET_Server_Client_t * cur; check(!server, GuNET_SERVER_ERROR_INVALID_ARGS); cur = server->clients; while (cur != NULL ) { GuNET_Server_Client_free(cur); cur = cur->next; } evutil_closesocket(server->fd); event_free(server->signal); event_free(server->listen); event_base_free(server->base); free(server); return GuNET_SERVER_ERROR_NONE; }
void ub_get_event_sys(struct ub_event_base* base, const char** n, const char** s, const char** m) { #ifdef USE_WINSOCK (void)base; *n = "event"; *s = "winsock"; *m = "WSAWaitForMultipleEvents"; #elif defined(USE_MINI_EVENT) (void)base; *n = "mini-event"; *s = "internal"; *m = "select"; #else struct event_base* b = AS_EVENT_BASE(base); *s = event_get_version(); # if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP) *n = "libev"; if (!b) b = (struct event_base*)ev_default_loop(EVFLAG_AUTO); # ifdef EVBACKEND_SELECT *m = ub_ev_backend2str(ev_backend((struct ev_loop*)b)); # else *m = "not obtainable"; # endif # elif defined(HAVE_EVENT_BASE_GET_METHOD) *n = "libevent"; if (!b) b = event_base_new(); *m = event_base_get_method(b); # else *n = "unknown"; *m = "not obtainable"; (void)b; # endif # ifdef HAVE_EVENT_BASE_FREE if (b && b != AS_EVENT_BASE(base)) event_base_free(b); # endif #endif }
pmix_event_base_t* pmix_start_progress_thread() { pmix_event_base_t *ev_base; /* Setup threading */ evthread_use_pthreads(); /* Create base for events */ if (NULL == (ev_base = (pmix_event_base_t*)event_base_new())) { PMIX_ERROR_LOG(PMIX_ERR_OUT_OF_RESOURCE); return NULL; } /* add an event it can block on */ if (0 > pipe(block_pipe)) { PMIX_ERROR_LOG(PMIX_ERR_IN_ERRNO); return NULL; } /* Make sure the pipe FDs are set to close-on-exec so that they don't leak into children */ if (pmix_fd_set_cloexec(block_pipe[0]) != PMIX_SUCCESS || pmix_fd_set_cloexec(block_pipe[1]) != PMIX_SUCCESS) { PMIX_ERROR_LOG(PMIX_ERR_IN_ERRNO); close(block_pipe[0]); close(block_pipe[1]); event_base_free(ev_base); return NULL; } event_assign(&block_ev, ev_base, block_pipe[0], EV_READ, wakeup, NULL); event_add(&block_ev, 0); evlib_active = true; block_active = true; /* fork off a thread to progress it */ if (0 > pthread_create(&engine, NULL, progress_engine, (void*)ev_base)) { PMIX_ERROR_LOG(PMIX_ERROR); return NULL; } if (!thread_initalized) { thread_initalized = true; } return ev_base; }
void *httpserver_dispatch(void *arg) { #ifndef MULTI_THREAD_SUPPORT struct event_base *base = (struct event_base *)arg; struct event *signal_event; signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base); if (!signal_event || event_add(signal_event, NULL)<0) { fprintf(stderr, "Could not create/add a signal event!\n"); return NULL; } #endif event_base_dispatch((struct event_base *) arg); #ifndef MULTI_THREAD_SUPPORT //evconnlistener_free(lmg_listener); event_free(signal_event); #endif event_base_free((struct event_base *) arg); return NULL; }
void TcpServer::Destroy() { if(_fd_listen != 0) { shutdown(_fd_listen, SD_BOTH); closesocket(_fd_listen); _fd_listen = 0; } if(_worker.get() != NULL) { event_base_loopbreak(_base); _worker->Wait(); _worker.reset(); } if(_base != NULL) { event_base_free(_base); _base = NULL; } }
void attach_namespace (int client, struct arguments arguments) { w(evutil_make_socket_closeonexec(client)); w(evutil_make_socket_nonblocking(client)); struct event_config *ev_config = p(event_config_new()); w(event_config_require_features(ev_config, EV_FEATURE_FDS)); struct event_base *ev_base = p(event_base_new_with_config(ev_config)); event_config_free(ev_config); struct event *ev_client = p(event_new(ev_base, client, EV_READ|EV_PERSIST, client_func, NULL)); struct arg arg = { .event = ev_client, .command = arguments.command }; w(event_assign(ev_client, ev_base, client, EV_READ|EV_PERSIST, client_func, &arg)); event_add(ev_client, NULL); w(event_base_dispatch(ev_base)); event_base_free(ev_base); }