Example #1
0
void on_read(int sock,short event,void *arg)
{
    sock_ev * psock_ev = (sock_ev*)arg;
    int ret = 0;
    
    do {
        ret = recv(sock,psock_ev->recvbuffer,BUFFERSIZE,0);
        if ( ret < 0 ) {
            std::cerr<<"recv failed ! error:"<<strerror(errno)<<std::endl;
            event_base_loopbreak(psock_ev->base);
            break;
        }
        if ( ret == 0 ) {
            debug_log("socket get read event!");
            ProcessData(psock_ev->recvbuffer);
            std::cerr<<"socket closed !: "<<strerror(errno)<<std::endl;
            event_base_loopbreak(psock_ev->base);
            break;
        }
        
        /**
         * recv bytes from proxy server
         * */
        std::cout<<"recv "<<ret<<" bytes from proxy server"<<std::endl;

    } while (0);

}
Example #2
0
static void sig_usr(int signo)
{
	if (signo == SIGINT)
	{
		printf("oops! catch CTRL+C!!!\n");
		event_base_loopbreak(base);
	}

	if (signo == SIGTERM)
	{
		printf("oops! being killed!!!\n");
		event_base_loopbreak(base);
	}
}
void cNetworkSingleton::Terminate(void)
{
	ASSERT(!m_HasTerminated);

	// Wait for the lookup thread to stop
	m_LookupThread.Stop();

	// Wait for the LibEvent event loop to terminate:
	event_base_loopbreak(m_EventBase);
	m_EventLoopThread.join();

	// Remove all objects:
	{
		cCSLock Lock(m_CS);
		m_Connections.clear();
		m_Servers.clear();
	}

	// Free the underlying LibEvent objects:
	event_base_free(m_EventBase);

	libevent_global_shutdown();

	// Set the HasTerminated flag:
	// (Only set the flag after everything has been removed, to avoid the random failures in the Google-test, caused by links terminating after this flag was set)
	m_HasTerminated = true;
}
Example #4
0
void core::curl_handler::stop()
{
    keep_working_ = false;

    event_base_loopbreak(event_base_);

    event_loop_thread_.join();

    for (auto& it : connections_)
    {
        const auto error = curl_multi_remove_handle(multi_handle_, it.first);
        assert(!error);
        (void*) error; // supress warning

        const auto& connection = it.second;
        boost::apply_visitor(completion_visitor(CURLE_ABORTED_BY_CALLBACK), connection->completion_handler_);
    }

    connections_.clear();

    while (!pending_jobs_.empty())
    {
        auto& job = pending_jobs_.top();
        boost::apply_visitor(completion_visitor(CURLE_ABORTED_BY_CALLBACK), job.completion_);
        pending_jobs_.pop();
    }
}
Example #5
0
void EventBase::terminateLoopSoon() {
  VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";

  if (!isRunning()) {
    return;
  }

  // Set stop to true, so the event loop will know to exit.
  // TODO: We should really use an atomic operation here with a release
  // barrier.
  stop_ = true;

  // Call event_base_loopbreak() so that libevent will exit the next time
  // around the loop.
  event_base_loopbreak(evb_);

  // If terminateLoopSoon() is called from another thread,
  // the EventBase thread might be stuck waiting for events.
  // In this case, it won't wake up and notice that stop_ is set until it
  // receives another event.  Send an empty frame to the notification queue
  // so that the event loop will wake up even if there are no other events.
  //
  // We don't care about the return value of trySendFrame().  If it fails
  // this likely means the EventBase already has lots of events waiting
  // anyway.
  try {
    queue_->putMessage(std::make_pair(nullptr, nullptr));
  } catch (...) {
    // We don't care if putMessage() fails.  This likely means
    // the EventBase already has lots of events waiting anyway.
  }
}
Example #6
0
static void listener_cli_cb(struct evconnlistener *listener,
                            evutil_socket_t fd, struct sockaddr *sa,
                            int socklen, void *user_data)
{
    struct event_base  *base = (struct event_base*)user_data;
    struct bufferevent *bev = NULL;
    struct sockaddr_in *sa_in = (struct sockaddr_in*)sa;

    UNUSED(listener);
    UNUSED(socklen);

#ifdef SOCKET_LIBEVENT_ENABLE_THREAD
    bev = bufferevent_socket_new(base, fd,
                                 BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
#else
    bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
#endif
    if (!bev) {
        fprintf(stderr, "Error constructing bufferevent!");
        event_base_loopbreak(base);
        return;
    }

    log_dbg("accept a cli connect");

    bufferevent_setcb(bev, cb_conn_read_cli, NULL, conn_eventcb_cli, NULL);
    bufferevent_enable(bev, EV_WRITE | EV_READ);
}
Example #7
0
void
resp_callback(thrash_client_t * cli, thrash_resp_t * resp)
{

    event_base_loopbreak(cli->evbase);
    printf("Done!\n");
}
Example #8
0
File: event.c Project: kghost/lldpd
static void
levent_stop(evutil_socket_t fd, short what, void *arg)
{
	struct event_base *base = arg;
	(void)fd; (void)what;
	event_base_loopbreak(base);
}
Example #9
0
void async_client::writable_callback_cb(int fd, short int events, void* arg) throw()
{
  client_context* context = static_cast<client_context*>(arg);
  async_client* client = context->client;
  context->write_exception.reset();

  try {
    client->writable_callback(fd, events);

  } catch (jubatus::exception::jubatus_exception& e) {
    event_del(&context->ev_write);
    client->sock_->disconnected();
    context->write_exception = e.thrower();

    try {
      throw;
    } catch (rpc_internal_error& e) {
      e << jubatus::exception::error_api_func("event_base_dispatch");
    } catch (...) {}

  } catch (...) {
    // unknown error
    event_del(&context->ev_write);
    event_base_loopbreak(context->evbase);
    context->write_exception = jubatus::exception::get_current_exception();
  }
}
Example #10
0
static void jmm_ctrl_c_wf_cb(evutil_socket_t fd, short what, void* ctx)
{
    struct event_base *base = ctx;


    event_base_loopbreak(base);
}
Example #11
0
bool DisconnectFromNovad()
{
	//Close out any possibly remaining socket artifacts
	if(libeventBase != NULL)
	{
		if(eventDispatchThread != 0)
		{
			if(event_base_loopbreak(libeventBase) == -1)
			{
				LOG(WARNING, "Unable to exit event loop", "");
			}
			pthread_join(eventDispatchThread, NULL);
			eventDispatchThread = 0;
		}
	}

	{
		Lock buffereventLock(&bufferevent_mutex);
		if(bufferevent != NULL)
		{
			//bufferevent_free(bufferevent);
			shutdown(IPCSocketFD, 2);
			bufferevent = NULL;
		}
	}

	MessageManager::Instance().DeleteEndpoint(IPCSocketFD);

	IPCSocketFD = -1;
	return true;
}
Example #12
0
void StopHTTPServer()
{
    LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
    if (workQueue) {
        LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
        workQueue->WaitExit();
        delete workQueue;
        workQueue = nullptr;
    }
    if (eventBase) {
        LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
        // Give event loop a few seconds to exit (to send back last RPC responses), then break it
        // Before this was solved with event_base_loopexit, but that didn't work as expected in
        // at least libevent 2.0.21 and always introduced a delay. In libevent
        // master that appears to be solved, so in the future that solution
        // could be used again (if desirable).
        // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
        if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
            LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
            event_base_loopbreak(eventBase);
        }
        threadHTTP.join();
    }
    if (eventHTTP) {
        evhttp_free(eventHTTP);
        eventHTTP = 0;
    }
    if (eventBase) {
        event_base_free(eventBase);
        eventBase = 0;
    }
    LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
}
Example #13
0
void EventBase::terminateLoopSoon() {
  VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";

  // Set stop to true, so the event loop will know to exit.
  stop_.store(true, std::memory_order_relaxed);

  // Call event_base_loopbreak() so that libevent will exit the next time
  // around the loop.
  event_base_loopbreak(evb_);

  // If terminateLoopSoon() is called from another thread,
  // the EventBase thread might be stuck waiting for events.
  // In this case, it won't wake up and notice that stop_ is set until it
  // receives another event.  Send an empty frame to the notification queue
  // so that the event loop will wake up even if there are no other events.
  //
  // We don't care about the return value of trySendFrame().  If it fails
  // this likely means the EventBase already has lots of events waiting
  // anyway.
  try {
    queue_->putMessage(nullptr);
  } catch (...) {
    // We don't care if putMessage() fails.  This likely means
    // the EventBase already has lots of events waiting anyway.
  }
}
static void	timeout_cb(evutil_socket_t fd, short event, void *arg) {
	if (g_flag)
		g_flag = 0;
	times++;
	if (times >= 5)
		event_base_loopbreak((struct event_base *)arg);
}
Example #15
0
/* Thread: scan */
static void
exit_cb(int fd, short event, void *arg)
{
  event_base_loopbreak(evbase_scan);

  scan_exit = 1;
}
Example #16
0
static void sighandler(int signal)
{
	(void)signal;
	/*printf("signal %d\n", signal);*/
	if(base != NULL)
		event_base_loopbreak(base);
}
void TcpTransport::exitBaseDispatch() {
  if (m_eventBase) {
    event_base_loopbreak(m_eventBase);
    // event_base_loopexit(m_eventBase, NULL);  //Note: memory leak will be
    // occured when timer callback was not done;
  }
}
Example #18
0
static void
abb_fwrite_multi_finish_cmpl(evutil_socket_t sock,
			     short flags,
			     void *priv)
{
	int ret;
	struct abb_fwrite_multi_finish_state *finish_state = priv;
	struct abb_io_multi_state *multi_state = finish_state->multi_state;

	ret = elasto_conn_op_rx(finish_state->ev_tx);
	if (ret < 0) {
		dbg(2, "block list put failed: %s\n", strerror(-ret));
		abb_io_multi_error_set(multi_state, ret);
	} else if (finish_state->op->rsp.is_error) {
		ret = elasto_fop_err_code_map(finish_state->op->rsp.err_code);
		dbg(2, "block list put error response: %d\n", ret);
		abb_io_multi_error_set(multi_state, ret);
	}
	elasto_conn_op_free(finish_state->ev_tx);
	op_free(finish_state->op);

	dbg(0, "multipart upload finished\n");

	ret = event_base_loopbreak(multi_state->ev_base);
	if (ret < 0) {
		dbg(0, "failed to break dispatch loop\n");
	}
	/* data_ctx cleanup after event loop exit */
}
Example #19
0
void shutdown_pgThread(PgThread * pgThread)
{
	event_base_loopbreak(pgThread->eventBase);
	pthread_mutex_lock(&pgThread->threadMutex);
	pthread_cond_signal(&pgThread->threadCond);
	pthread_mutex_unlock(&pgThread->threadMutex);
}
Example #20
0
static void
abb_io_multi_tx_pipe_fill(struct abb_io_multi_state *multi_state)
{
	int ret;

	while ((multi_state->in_flight < multi_state->max_in_flight)
					&& (multi_state->data_remain > 0)) {
		uint64_t this_off = multi_state->off
					+ multi_state->data_off;
		uint64_t this_len = MIN(multi_state->max_io,
					multi_state->data_remain);

		dbg(0, "multi fwrite: off=%" PRIu64 ", len=%" PRIu64 "\n",
		    this_off, this_len);

		ret = abb_fwrite_multi_tx(multi_state, this_off, this_len);
		if (ret < 0) {
			goto err_break;
		}

		multi_state->data_off += this_len;
		multi_state->data_remain -= this_len;
		multi_state->in_flight++;
	}

	return;

err_break:
	abb_io_multi_error_set(multi_state, ret);
	ret = event_base_loopbreak(multi_state->ev_base);
	if (ret < 0) {
		dbg(0, "failed to break dispatch loop\n");
	}
	/* data_ctx cleanup after event loop exit */
}
Example #21
0
void TNonblockingIOThread::breakLoop(bool error) {
  if (error) {
    GlobalOutput.printf(
      "TNonblockingServer: IO thread #%d exiting with error.", number_);
    // TODO: figure out something better to do here, but for now kill the
    // whole process.
    GlobalOutput.printf("TNonblockingServer: aborting process.");
    ::abort();
  }

  // sets a flag so that the loop exits on the next event
  event_base_loopbreak(eventBase_);

  // event_base_loopbreak() only causes the loop to exit the next time
  // it wakes up.  We need to force it to wake up, in case there are
  // no real events it needs to process.
  //
  // If we're running in the same thread, we can't use the notify(0)
  // mechanism to stop the thread, but happily if we're running in the
  // same thread, this means the thread can't be blocking in the event
  // loop either.
  if (!Thread::is_current(threadId_)) {
    notify(NULL);
  }
}
Example #22
0
void signal_cb(evutil_socket_t fd, short what, void *arg)
{
    mdebug("signal_cb");
    struct event_base *base = (struct event_base *)arg;
    event_base_loopbreak(base);
    dispatch_conn_new(-1, 'k', NULL);
}
Example #23
0
void pmix_stop_progress_thread(pmix_event_base_t *ev_base)
{
    int i;

    if (!thread_initalized) {
        /* nothing we can do */
        return;
    }

    /* mark it as inactive */
    evlib_active = false;
    /* if present, use the block to break it loose just in
     * case the thread is blocked in a call to select for
     * a long time */
    if (block_active) {
        i=1;
        write(block_pipe[1], &i, sizeof(int));
    }
    /* break the event loop - this will cause the loop to exit
     * upon completion of any current event */
    event_base_loopbreak(ev_base);
    /* wait for thread to exit */
    pthread_join(engine, NULL);
    if (block_active) {
        /* delete the blocking event */
        event_del(&block_ev);
        block_active = false;
    }
    /* close the pipes */
    close(block_pipe[0]);
    close(block_pipe[1]);
    return;
}
Example #24
0
void signal_handler(evutil_socket_t fd, short what, void *arg) {
    struct client_state *state = (struct client_state*) arg;
    if (what&EV_SIGNAL) {
        event_base_loopbreak(state->base);
        printf("Stop client\n");
    }
}
void InterruptTorControl()
{
    if (base) {
        LogPrintf("tor: Thread interrupt\n");
        event_base_loopbreak(base);
    }
}
Example #26
0
void CSockPairEvent::exitMonitorCB(evutil_socket_t, short, void *arg)
{
    CSockPairEvent *pParam = (CSockPairEvent*)arg;

    switch(pParam->getRunStatus())
    {
    case RUNSTATUS_STOPPING:
        {
            if (!pParam->getRunOnStop())
            {
                Q_Printf("ready stop thread %u.", Q_ThreadID());
                pParam->onStop();
                pParam->setRunOnStop(true);
            }
        }
        break;

    case RUNSTATUS_STOPPED:
        {
            Q_Printf("stop thread %u successfully.", Q_ThreadID());
            event_base_loopbreak(pParam->getBase());
        }
        break;

    default:
        break;
    }
}
Example #27
0
File: net.c Project: aido/picocoin
static void nc_conn_kill(struct nc_conn *conn)
{
	assert(conn->dead == false);

	conn->dead = true;
	event_base_loopbreak(conn->nci->eb);
}
Example #28
0
Client::Client(struct event_base* base, evutil_socket_t fd, struct sockaddr *socket, int socket_len)
{
	m_buffer = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
	if (!m_buffer) 
	{
		fprintf(stderr, "Error constructing bufferevent!");
		event_base_loopbreak(base);
		throw;
	}
	
	bufferevent_setcb(m_buffer, conn_readcb, conn_writecb, conn_eventcb, this);
	bufferevent_enable(m_buffer, EV_READ|EV_WRITE);
//	bufferevent_setwatermark(m_buffer, EV_READ, 128, 0);
	
	struct timeval time1, time2;
//	time1.tv_sec = 10;
//	time2.tv_sec = 11;
//	bufferevent_set_timeouts(m_buffer, &time1, &time2);
	
	if(socket->sa_family == AF_INET)
	{
		struct sockaddr_in *socket4 = (struct sockaddr_in*)socket;
		m_ip = string(inet_ntoa(socket4->sin_addr));
		m_port = ntohs(socket4->sin_port);
	}
	
	bufferevent_write(m_buffer, "hello", strlen("hello"));//tmp
	
}
Example #29
0
/* Thread: httpd */
static void
exit_cb(int fd, short event, void *arg)
{
  event_base_loopbreak(evbase_httpd);

  httpd_exit = 1;
}
Example #30
0
/* SIGCHLD callback */
static void sigchld_cb(evutil_socket_t fd, short what, void *arg)
{
    int status;
    pid_t pid;

    LOG(log_debug, logtype_afpd, "Got SIGCHLD event");
  
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
        if (WIFEXITED(status)) {
            if (WEXITSTATUS(status))
                LOG(log_info, logtype_afpd, "child[%d]: exited %d", pid, WEXITSTATUS(status));
            else
                LOG(log_info, logtype_afpd, "child[%d]: done", pid);
        } else {
            if (WIFSIGNALED(status))
                LOG(log_info, logtype_afpd, "child[%d]: killed by signal %d", pid, WTERMSIG(status));
            else
                LOG(log_info, logtype_afpd, "child[%d]: died", pid);
        }

        if (pid == afpd_pid)
            afpd_pid = -1;
        else if (pid == cnid_metad_pid)
            cnid_metad_pid = -1;
        else
            LOG(log_error, logtype_afpd, "Bad pid: %d", pid);
    }

    if (in_shutdown && afpd_pid == -1 && cnid_metad_pid == -1)
        event_base_loopbreak(base);
}