struct event_base *get_fd_rdy_event_base(void) { struct event_config *evcfg = event_config_new(); event_config_require_features(evcfg, EV_FEATURE_FDS); struct event_base *base = event_base_new_with_config(evcfg); event_config_free(evcfg); return base; }
Bool HawkGateThread::Init(UInt32 iBaseId) { HawkAssert(!m_pThread && !m_pBase && !m_pZmq); m_iBaseSid = iBaseId; //创建通用缓冲 if (!m_pOctets) m_pOctets = new OctetsStream(m_pGateway->GetBufSize()); //创建线程 if (!m_pThread) m_pThread = new HawkThread(hawk_GateThreadRoutine); //创建事件基础对象 if (!m_pBase) { event_config* pCfg = event_config_new(); if (!pCfg) { HawkPrint("Create EventConfig Failed."); return false; } #ifdef PLATFORM_LINUX event_config_require_features(pCfg, EV_FEATURE_ET); #endif event_config_set_flag(pCfg, EVENT_BASE_FLAG_NOLOCK); m_pBase = (void*)event_base_new_with_config(pCfg); event_config_free(pCfg); if (!m_pBase) { HawkPrint("Create EventBase Failed."); return false; } if (m_iBaseSid == 1) { const Char* pszMethod = event_base_get_method((event_base*)m_pBase); if (pszMethod && strlen(pszMethod)) { HawkFmtPrint("Kernel Event Notification Mechanism: %s", pszMethod); } } } //创建ZMQ对象 if (!m_pZmq) { m_pZmq = P_ZmqManager->CreateZmq(HawkZmq::HZMQ_DEALER); m_pZmq->SetIdentity(&m_iBaseSid, sizeof(m_iBaseSid)); m_pZmq->Connect(m_pGateway->GetThreadZmqAddr()); } return true; }
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); }
int main(int argc, char **argv) { struct event_base *base; struct event_config *cfg; struct event *ev; const char *test = "test string"; evutil_socket_t pair[2]; /* Initialize the library and check if the backend supports EV_FEATURE_EARLY_CLOSE */ cfg = event_config_new(); event_config_require_features(cfg, EV_FEATURE_EARLY_CLOSE); base = event_base_new_with_config(cfg); event_config_free(cfg); if (!base) { /* Backend doesn't support EV_FEATURE_EARLY_CLOSE */ return 0; } /* Create a pair of sockets */ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) return (1); /* Send some data on socket 0 and immediately close it */ if (send(pair[0], test, (int)strlen(test)+1, 0) < 0) return (1); shutdown(pair[0], SHUT_WR); /* Dispatch */ ev = event_new(base, pair[1], EV_CLOSED | EV_TIMEOUT, closed_cb, event_self_cbarg()); event_add(ev, &timeout); event_base_dispatch(base); /* Finalize library */ event_base_free(base); return 0; }
/* * The actual main function. */ int sntp_main ( int argc, char **argv, const char *sntpVersion ) { int i; int exitcode; int optct; struct event_config * evcfg; /* Initialize logging system - sets up progname */ sntp_init_logging(argv[0]); if (!libevent_version_ok()) exit(EX_SOFTWARE); init_lib(); init_auth(); optct = ntpOptionProcess(&sntpOptions, argc, argv); argc -= optct; argv += optct; debug = OPT_VALUE_SET_DEBUG_LEVEL; TRACE(2, ("init_lib() done, %s%s\n", (ipv4_works) ? "ipv4_works " : "", (ipv6_works) ? "ipv6_works " : "")); ntpver = OPT_VALUE_NTPVERSION; steplimit = OPT_VALUE_STEPLIMIT / 1e3; gap.tv_usec = max(0, OPT_VALUE_GAP * 1000); gap.tv_usec = min(gap.tv_usec, 999999); if (HAVE_OPT(LOGFILE)) open_logfile(OPT_ARG(LOGFILE)); msyslog(LOG_INFO, "%s", sntpVersion); if (0 == argc && !HAVE_OPT(BROADCAST) && !HAVE_OPT(CONCURRENT)) { printf("%s: Must supply at least one of -b hostname, -c hostname, or hostname.\n", progname); exit(EX_USAGE); } /* ** Eventually, we probably want: ** - separate bcst and ucst timeouts (why?) ** - multiple --timeout values in the commandline */ response_timeout = OPT_VALUE_TIMEOUT; response_tv.tv_sec = response_timeout; response_tv.tv_usec = 0; /* IPv6 available? */ if (isc_net_probeipv6() != ISC_R_SUCCESS) { ai_fam_pref = AF_INET; TRACE(1, ("No ipv6 support available, forcing ipv4\n")); } else { /* Check for options -4 and -6 */ if (HAVE_OPT(IPV4)) ai_fam_pref = AF_INET; else if (HAVE_OPT(IPV6)) ai_fam_pref = AF_INET6; } /* TODO: Parse config file if declared */ /* ** Init the KOD system. ** For embedded systems with no writable filesystem, ** -K /dev/null can be used to disable KoD storage. */ kod_init_kod_db(OPT_ARG(KOD), FALSE); // HMS: Should we use arg-defalt for this too? if (HAVE_OPT(KEYFILE)) auth_init(OPT_ARG(KEYFILE), &keys); /* ** Considering employing a variable that prevents functions of doing ** anything until everything is initialized properly ** ** HMS: What exactly does the above mean? */ event_set_log_callback(&sntp_libevent_log_cb); if (debug > 0) event_enable_debug_mode(); #ifdef WORK_THREAD evthread_use_pthreads(); /* we use libevent from main thread only, locks should be academic */ if (debug > 0) evthread_enable_lock_debuging(); #endif evcfg = event_config_new(); if (NULL == evcfg) { printf("%s: event_config_new() failed!\n", progname); return -1; } #ifndef HAVE_SOCKETPAIR event_config_require_features(evcfg, EV_FEATURE_FDS); #endif /* all libevent calls are from main thread */ /* event_config_set_flag(evcfg, EVENT_BASE_FLAG_NOLOCK); */ base = event_base_new_with_config(evcfg); event_config_free(evcfg); if (NULL == base) { printf("%s: event_base_new() failed!\n", progname); return -1; } /* wire into intres resolver */ worker_per_query = TRUE; addremove_io_fd = &sntp_addremove_fd; open_sockets(); if (HAVE_OPT(BROADCAST)) { int cn = STACKCT_OPT( BROADCAST ); const char ** cp = STACKLST_OPT( BROADCAST ); while (cn-- > 0) { handle_lookup(*cp, CTX_BCST); cp++; } } if (HAVE_OPT(CONCURRENT)) { int cn = STACKCT_OPT( CONCURRENT ); const char ** cp = STACKLST_OPT( CONCURRENT ); while (cn-- > 0) { handle_lookup(*cp, CTX_UCST | CTX_CONC); cp++; } } for (i = 0; i < argc; ++i) handle_lookup(argv[i], CTX_UCST); gettimeofday_cached(base, &start_tv); event_base_dispatch(base); event_base_free(base); if (!time_adjusted && (ENABLED_OPT(STEP) || ENABLED_OPT(SLEW))) exitcode = 1; else exitcode = 0; return exitcode; }
int main(int argc, char* argv[]) { #if 1 // For debug with segment fault struct sigaction sa; sa.sa_handler = backtrace_info; sigaction(SIGSEGV, &sa, NULL); // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif int opt_g = 0; memset(&cltopt, 0, sizeof(CLT_OPT)); cltopt.C_TYPE = C_USR; while( (opt_g = getopt(argc, argv, "Dh")) != -1 ) { switch(opt_g) { case 'D': cltopt.C_TYPE = C_DAEMON; break; case 'h': default: usage(); exit(EXIT_SUCCESS); } } if(load_settings_client(&cltopt) == RET_NO) { st_d_error("加载配置文件settings.json出错!"); exit(EXIT_FAILURE); } OpenSSL_add_ssl_algorithms(); SSL_load_error_strings(); SSL_library_init(); //SSL_library_init() always returns "1" //int sd_id128_from_string(const char *s, sd_id128_t *ret); sd_id128_get_machine(&cltopt.mach_uuid); gethostname(cltopt.hostname, sizeof(cltopt.hostname)); st_d_print("CURRENT MACH_ID:%s, HOSTNAME:%s", SD_ID128_CONST_STR(cltopt.mach_uuid), cltopt.hostname); if (cltopt.C_TYPE == C_DAEMON) { cltopt.session_uuid = cltopt.mach_uuid; st_d_print("PLEASE REMEMEBER SET MACH_ID FOR USER TYPE!"); } dump_clt_opts(&cltopt); /*带配置产生event_base对象*/ struct event_config *cfg; cfg = event_config_new(); event_config_avoid_method(cfg, "select"); //避免使用select event_config_require_features(cfg, EV_FEATURE_ET); //使用边沿触发类型 base = event_base_new_with_config(cfg); event_config_free(cfg); st_d_print("当前复用Event模式: %s", event_base_get_method(base)); // epoll /*连接服务器*/ int srv_fd = socket(AF_INET, SOCK_STREAM, 0); unsigned int optval = 1; setsockopt(srv_fd, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval));//禁用NAGLE算法 if(sc_connect_srv(srv_fd) != RET_YES) { SYS_ABORT("连接服务器失败!"); } if(cltopt.C_TYPE == C_DAEMON) { if (sc_daemon_init_srv(srv_fd) != RET_YES) SYS_ABORT("(Daemon) 服务器返回错误!"); } else { if (sc_usr_init_srv(srv_fd) != RET_YES) SYS_ABORT("(Usr) 服务器返回错误!"); } st_d_print("客户端连接服务器OK!"); /** * USR 建立本地Listen侦听套接字 */ if (cltopt.C_TYPE == C_USR) { int i = 0; for (i=0; i<MAX_PORT_NUM; i++) { if (cltopt.maps[i].usrport) { struct evconnlistener *listener; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(cltopt.maps[i].usrport); /* Port Num */ listener = evconnlistener_new_bind(base, accept_conn_cb, &cltopt.maps[i], LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1/*backlog 连接无限制*/, (struct sockaddr*)&sin, sizeof(sin)); if (!listener) { st_d_error("[USR]创建侦听套接字失败 %d:%d", cltopt.maps[i].usrport, cltopt.maps[i].daemonport); continue; } evconnlistener_set_error_cb(listener, accept_error_cb); st_d_print("[USR]创建侦听套接字 %d:%d OK", cltopt.maps[i].usrport, cltopt.maps[i].daemonport); } else break; } } encrypt_init(SD_ID128_CONST_STR(cltopt.mach_uuid), cltopt.enc_key); if (cltopt.C_TYPE == C_DAEMON && cltopt.ss5_port ) { /** * 目前只考虑将sockets5代理使用线程池来处理,其它的端口暴露 * 基本都是长连接,不单独处理 */ cltopt.thread_num = 5; cltopt.main_thread_id = pthread_self(); cltopt.thread_objs = (P_THREAD_OBJ)calloc(sizeof(THREAD_OBJ), cltopt.thread_num); if (!cltopt.thread_objs) { SYS_ABORT("申请THREAD_OBJ出错"); } sc_create_ss5_worker_threads(cltopt.thread_num, cltopt.thread_objs); st_d_print("[DAEMON]创建sockets5代理端口:%d", cltopt.ss5_port); struct evconnlistener *listener; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(cltopt.ss5_port); /* Port Num */ listener = evconnlistener_new_bind(base, ss5_accept_conn_cb, NULL, LEV_OPT_LEAVE_SOCKETS_BLOCKING/* 阻塞 */|LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1/*backlog 连接无限制*/, (struct sockaddr*)&sin, sizeof(sin)); if (!listener) { st_d_error("[DAEMON]sockets5代理创建侦听套接字失败 %d", cltopt.ss5_port); exit(EXIT_FAILURE); } evconnlistener_set_error_cb(listener, accept_error_cb); st_d_print("[DAEMON]sockets5代理创建侦听套接字OK %d", cltopt.ss5_port); } if (cltopt.C_TYPE == C_DAEMON && cltopt.dns_port) { st_d_print("[DAEMON]创建DNS代理端口:%d", cltopt.dns_port); if (cltopt.dns_port != 53) { st_d_print("[DAEMON]请注意标准DNS侦听#53端口!"); } int dns_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (dns_socket < 0 ) { st_d_error("Create DNS socket error!"); exit(EXIT_FAILURE); } unsigned int optval = 1; setsockopt(dns_socket, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval));//禁用NAGLE算法 setsockopt(dns_socket, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)); evutil_make_socket_closeonexec(dns_socket); evutil_make_socket_nonblocking(dns_socket); struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(cltopt.dns_port); /* Port Num */ if (bind(dns_socket, (struct sockaddr *)&sin, sizeof(sin))) { st_d_error("Bind DNS socket error!"); exit(EXIT_FAILURE); } cltopt.dns_transid_port_map = (unsigned short*)malloc(sizeof(unsigned short) * 0xFFFF); if (!cltopt.dns_transid_port_map) { st_d_error("Malloc for requestid-port failed!"); exit(EXIT_FAILURE); } P_PORTTRANS p_trans = sc_create_trans(cltopt.dns_port); if (!p_trans) { st_d_error("本地无空闲TRANS!"); exit(EXIT_FAILURE); } p_trans->is_enc = 1; p_trans->l_port = cltopt.dns_port; encrypt_ctx_init(&p_trans->ctx_enc, p_trans->l_port, cltopt.enc_key, 1); encrypt_ctx_init(&p_trans->ctx_dec, p_trans->l_port, cltopt.enc_key, 0); // 建立DNS UDP事件侦听 p_trans->extra_ev = event_new(base, dns_socket, EV_READ | EV_PERSIST, dns_client_to_proxy_cb, p_trans); int dns_srv_fd = socket(AF_INET, SOCK_STREAM, 0); if(sc_connect_srv(dns_srv_fd) != RET_YES) { SYS_ABORT("连接服务器失败!"); } sc_daemon_dns_init_srv(dns_srv_fd, p_trans->l_port, 12333); evutil_make_socket_nonblocking(dns_srv_fd); // later enabled //event_add(p_trans->extra_ev, NULL) != 0); p_trans->srv_bev = bufferevent_socket_new(base, dns_srv_fd, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(p_trans->srv_bev, dns_bufferread_cb_enc, NULL, dns_bufferevent_cb, p_trans); st_d_print("[DAEMON]DNS代理创建侦听套接字OK %d", cltopt.dns_port); } sc_set_eventcb_srv(srv_fd, base); /** * Main Loop Here */ event_base_loop(base, 0); event_base_free(base); st_d_print("程序退出!!!!"); return 0; }
static bool HHVM_METHOD(EventConfig, requireFeatures, int64_t feature) { InternalResourceData *event_config_resource_data = FETCH_RESOURCE(this_, InternalResourceData, s_event_config); return event_config_require_features((event_config_t *) event_config_resource_data->getInternalResourceData(), feature) == 0?true:false; }
int game_event_init() { int ret = 0; struct event_config *config = NULL; // struct event *event_signal1 = NULL; // struct event *event_signal2 = NULL; event_set_log_callback(libevent_log); config = event_config_new(); if (!config) { log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: event_config_new failed[%d]", __FUNCTION__, __LINE__, errno); ret = -10; goto fail; } event_config_require_features(config, EV_FEATURE_ET | EV_FEATURE_O1 /*| EV_FEATURE_FDS*/); event_config_set_flag(config, EVENT_BASE_FLAG_NOLOCK | EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST); base = event_base_new_with_config(config); if (!base) { log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: event_base_new_with_config failed[%d]", __FUNCTION__, __LINE__, errno); ret = -20; goto fail; } /* event_signal1 = evsignal_new(base, SIGUSR1, cb_signal, NULL); if (!event_signal1) { log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: evsignal_new failed[%d]", __FUNCTION__, __LINE__, errno); ret = -30; goto fail; } event_signal2 = evsignal_new(base, SIGUSR2, cb_signal, NULL); if (!event_signal2) { log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: evsignal_new failed[%d]", __FUNCTION__, __LINE__, errno); ret = -30; goto fail; } // struct event event_signal, event_timer; // evsignal_assign(&event_signal, base, SIGUSR1, cb_signal, NULL); // evtimer_assign(&event_timer, base, cb_timer, NULL); evsignal_add(event_signal1, NULL); evsignal_add(event_signal2, NULL); */ return (0); fail: /* if (event_signal1) { event_free(event_signal1); event_signal1 = NULL; } if (event_signal2) { event_free(event_signal2); event_signal2 = NULL; } */ if (config) { event_config_free(config); config = NULL; } if (base) { event_base_free(base); base = NULL; } return (ret); }
bool EventLoopL::Prepare() { _DBG("EventLoopL::Prepare"); if(!EventConfig_) { EventConfig_ = event_config_new(); } if(!EventConfig_) { throwSystemError("event_config_new allocate fail!"); } //event_config_avoid_method(EventConfig_, "select");//avoid select //event_config_avoid_method(EventConfig_, "poll");//avoid poll if(0 != event_config_require_features(EventConfig_, EV_FEATURE_O1))//EV_FEATURE_ET ? { _ERR("set event config feature fail!"); return false; } if(0 != event_config_set_flag(EventConfig_, EVENT_BASE_FLAG_NOLOCK)) { _ERR("set event config flag fail!"); return false; } if(!EventBase_) { EventBase_ = event_base_new_with_config(EventConfig_); } if(!EventBase_) { throwSystemError("event_base_new_with_config allocate fail!"); return false; } _DBG("Current used method : %s", event_base_get_method(EventBase_)); for(auto &data : Datas_) { if(data) { std::shared_ptr<IO> io(data->io.lock()); if(!io) { _WRN("This io %d is not exist!", io->Index()); continue; } if(io->Index() < 0) { _ERR("This IO has been removed!"); continue; } if(data->ev) { event_del(data->ev); event_free(data->ev); data->ev = NULL; } event* ev = event_new(EventBase_, io->Fd(), io->Condition(), CEventCallBack, (void*)&(data->fn)); _DBG("Add io %p(index : %d fd : %d cond : %d)", ev, io->Index(), io->Fd(), io->Condition()); if(ev == NULL) { _ERR("event_new fail, index %d", io->Index()); continue; } data->ev = ev; if(event_add(ev, NULL)) { _ERR("event_add fail, index %d!", io->Index()); continue; } } } int evtfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if (evtfd < 0) { _ERR("Get eventfd fail!"); return false; } Wakeup_.reset(new IO(evtfd, EV_READ | EV_PERSIST)); Wakeup_->SetCallback(std::bind(&EventLoopL::quitAsync, this, std::placeholders::_1)); AddIO(Wakeup_); return true; }