int LoadConfigEngine::ThreadMain(void *pArg)
{
	ssize_t len                     = 0;
    ssize_t evl                     = 0;
    struct inotify_event * event    = NULL;

    LoadConfigEngine* loadConfigEngine = static_cast<LoadConfigEngine*>(pArg);

    while (!IsStop()) 
	{		
        UnInit();
        if (RET_ERROR == Init())
		{
            sleep(3);
            continue;
        }
		
        len = read(m_fd, m_buf, INOTIFY_BUFLEN);
        g_log.Log(DEBUG, "[%s-%d-%s]:Config file %s is modified , read: [%d]", __FILE__, __LINE__, __FUNCTION__,  SCAN_CONFIG_FILENAME, len);
        if (len > 0) 
		{
            evl = 0;
            while (evl < len) 
			{
                event = (struct inotify_event*)(&m_buf[evl]);

				sleep(1);
                if ( RET_SUCCESS != loadConfigEngine->LoadServerConfig())
				{
					g_log.Log(ERROR, "[%s-%d-%s]: Load config %s error, please check the config file.",  __FILE__, __LINE__, __FUNCTION__, SCAN_CONFIG_FILENAME);
				}
     
                evl += INOTIFY_EVENT_SIZE + event->len;
	        }
        }
		else if (0 == len) 
        {
            UnInit();
            g_log.Log(ERROR, "[%s-%d-%s]: read fd is closed, try open again...", __FILE__, __LINE__, __FUNCTION__);
        }
		else
		{
            if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
        	{
                continue;
        	}
            else
			{	
				//TODO some thing
               UnInit();
               g_log.Log(ERROR, "[%s-%d-%s]: read %s error: %d, try open again...", __FILE__, __LINE__, __FUNCTION__,  SCAN_CONFIG_FILENAME, errno);
            }
        }
		
		sleep(1);
		
	}

	return RET_SUCCESS;
}
Ejemplo n.º 2
0
void PingThread::ManagerFunc()
{
	if(!IsStop())
	{
		PingMessage msg(&m_connector->m_handler);
		m_connector->toMessage(msg);
	}
}
Ejemplo n.º 3
0
//============================================================
// <T>逻辑处理。</T>
//
// @return 处理结果
//============================================================
TResult FRenderThread::Process(){
   while(!IsStop()){
      TBool statusPause = RDeviceManager::Instance().StatusPause();
      if(!statusPause){
         _pWindow->ProcessRender();
      }
      SleepMicro(_interval);
   }
   return ESuccess;
}
Ejemplo n.º 4
0
//============================================================
// <T>逻辑处理。</T>
//
// @return 处理结果
//============================================================
TResult FProcessorThread::Process(){
   while(!IsStop()){
      TBool statusPause = RDeviceManager::Instance().StatusPause();
      if(!statusPause){
         // 执行处理
         _locker.Enter();
         _pLooper->Record();
         for(TInt n = 0; n < _looperLimit; n++){
            IProcessor* pProcessor = _pLooper->Next();
            if(pProcessor == NULL){
               break;
            }
            if(!IsStop()){
               pProcessor->AnsyProcess();
            }
         }
         _locker.Leave();
      }
      // 休息处理
      SleepMicro(_interval);
   }
   return ESuccess;
}
//============================================================
// <T>网络链接监听处理。</T>
//
// @return 执行结果
//============================================================
TInt FNetEpollTransferServerThread::Process(){
   MO_ASSERT(_pService);
   // 链接端口
   _pServerSocket->SetHost(_host.host);
   _pServerSocket->SetPort(_host.port);
   _pServerSocket->Connect();
   _pServerSocket->SetNonBlock();
   MO_DEBUG("Create tcp server. (host=%s:%d, handle=%d)",
      (TCharC*)_host.host, _host.port, _pServerSocket->Handle());
   // 设置信息
   TFsNetSocketInfoVector infos;
   TInt infoSize = infos.Size();
   // 安装扑捉器
   _pCatcher->Install();
   // 监听输入端口
   while(!IsStop()){
      _pCatcher->Enter();
      if(MO_TRAP_CATCHER(_pCatcher)){
         _pCatcher->Recorded();
         //............................................................
         // 接收多个请求
         infos.Clear();
         for(TInt n = 0; n < infoSize; n++){
            SNetSocketInfo info;
            RType<SNetSocketInfo>::Clear(&info);
            if(_pServerSocket->Accept(info)){
               infos.Push(info);
            }else{
               break;
            }
         }
         // 增加网络链接
         if(!infos.IsEmpty()){
            _pService->AddSockets(infos);
         }else{
            MO_LIB_MICRO_SLEEP(MO_MD_NTS_ACCEPT_INTERVAL);
         }
      }else{
         _pCatcher->JumpFinish();
      }
      _pCatcher->Leave();
   }
   return ESuccess;
}
void ExternalConnectThread::ThreadFunc()
{
	m_udpSocket = m_address.m_socketFactory->CreateSocket();
	UDPSocket* socket = dynamic_cast<UDPSocket*>(m_udpSocket);
	if(!socket || !socket->Bind(m_address.m_localIP, m_address.m_localPort))
	{
		SignalError();
		return;
	}

	socket->SetSendAddr(m_address.m_ip, m_address.m_port);
	std::string data = m_address.m_moduleName;
	int size = m_address.m_moduleName.size();
	while(!IsStop())
	{
		if(m_changeAddr.Wait(1000) == Semaphore::TIMEOUT)
		{
			if (!socket->Send((char*)&size, sizeof(size)) ||
				!socket->Send((char*)data.c_str(), data.size() * sizeof(char)))
			{
				SignalError();
				return;
			}
		}
		else
		{
			break;
		}
	}

	UDTSecureSocketFactory* udtSocketFactory = dynamic_cast<UDTSecureSocketFactory*>(m_address.m_socketFactory);
	if(!udtSocketFactory)
	{
		SignalError();
		return;
	}


	udtSocketFactory->SetUdpSocket(socket->GetSocket());
	m_csSocket.Enter();
	m_udpSocket = 0;
	m_csSocket.Leave();
	ConnectThread::ThreadFunc();
}
//============================================================
// <T>网络数据接收处理。</T>
//
// @return 处理结果
//============================================================
TResult FNetSingleSocketReceiveThread::Process(){
   // 读取服务信息
   MO_ASSERT(_pService);
   STransferServiceConfig& config = _pService->Config();
   _dataCheck = config.dataCheck;
   _dataCompress = config.dataCompress;
   _dataMask = config.dataMask;
   // 获得网络端口信息
   MO_ASSERT(_pSocket);
   // 获得链接管理模块
   FNetBufferedSocketModule* pSocketsModule = _pService->SocketsModule();
   MO_ASSERT(pSocketsModule);
   // 获得接收链接管道
   FQueue* pReceiveQueue = _pService->ReceiveNodeQueue();
   MO_ASSERT(pReceiveQueue);
   // 获得主输入队列
   _pInputQueue = _pService->QueueStorage()->Connection()->InputQueue();
   MO_ASSERT(_pInputQueue);
   while(!IsStop()){
      SNetSocketInfo* pSocketInfo = _pSocket->Info();
      TUint64 lastReceiveTotal = pSocketInfo->receiveTotal;
      TInt length = _pSocket->DoBufferReceive();
      if(length > 0){
         _receiveTotal += length;
         // 接收首次数据
         if(0 == lastReceiveTotal){
            ReceiveFirstData(_pSocket);
         }
         // 收到数据处理
         ReceiveData(_pSocket);
      }else if(length < 0){
         // 链接关闭处理
         MO_INFO(TC("Epoll socket receive disconnect. (socket=0x%08X, length=%d)"), _pSocket, length);
         _pService->CloseSocketWithNotify(_pSocket);
         break;
      }
   }
   return ESuccess;
}
Ejemplo n.º 8
0
Archivo: main.cpp Proyecto: tkai8/asos
void * http_event_loop(void *arg){
  int event_thread_id = (*(int *)arg);
  int sock;
  
  ssize_t read_size;

  int request_counter=0;

  int event_num;
  int max_events = 10;
  int i;
  int ret;
  EpollManager *epoll_mng;

  Connection *conn = NULL;

  struct epoll_event events[max_events];
  for(i=0; i<max_events; i++){
    memset(&events[i], 0, sizeof(events[i]));    
  }

  epoll_mng = server->getEpoll(event_thread_id);
  if(epoll_mng == NULL){
    printf("Error: getEpoll returned -1\n");
    exit(-1);
  }

  while(1){

    event_num = epoll_wait(epoll_mng->epoll, events, max_events, EPOLL_WAIT_TIMEOUT_MSEC);

    if(event_num == -1){ perror("epoll_wait"); break; }
    if(IsStop()){ break; }

    //printf("##### epoll wait : event num = %d\n", event_num);

    for(i=0; i<event_num; i++){
      conn = (Connection *)events[i].data.ptr;
      if(conn == NULL){
	printf("Error: epoll event do not have connection\n");
	exit(-1);
      }
      sock = conn->sock;
      
      if(events[i].events & EPOLLIN){
	// Read
	ret = conn->Read();
	if(ret <= 0 ){ epoll_mng->CloseConnection(conn);  delete conn;  conn = NULL; continue; }

	// Process
	ret = conn->Process();
	if(ret <= 0 ){ epoll_mng->CloseConnection(conn);  delete conn;  conn = NULL; continue; }	
      }

      if(events[i].events & EPOLLOUT){
	// Send
	ret = conn->Send();
	if(ret <= 0 ){ epoll_mng->CloseConnection(conn);  delete conn;  conn = NULL; continue; }
      }

      if((events[i].events & EPOLLRDHUP) || 
	 (events[i].events & EPOLLERR)   || 
	 (events[i].events & EPOLLHUP) ){
	epoll_mng->CloseConnection(conn);  delete conn;  conn = NULL;
	continue;
      }
    }

    epoll_mng->CheckAndCloseConnections();

  }

  pthread_exit(NULL);
}
Ejemplo n.º 9
0
int CDiscoveryApp::udpServer( void )
{
	/* Variable and structure definitions. */
	
	int sd, rc;
	struct sockaddr_in serveraddr, clientaddr;
	int clientaddrlen = sizeof(clientaddr);
	int serveraddrlen = sizeof(serveraddr);    
	
	int buflen = sizeof(DiscoveryResponse_Msg);
	
	
	unsigned char buffer[1000]={0};
	unsigned char *bufptr = buffer;
	
	if((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		LOG ("UDP server - socket() error %s", strerror(errno));
		return -1;
	}

	memset(&serveraddr, 0x00, serveraddrlen);
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(SERVPORT);
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if((rc = bind(sd, (struct sockaddr *)&serveraddr, serveraddrlen)) < 0)
	{
		LOG ("UDP server - bind() error %s", strerror(errno));
		close(sd);
		return -1;
	}
	
	LOG("Using IP %s and port %d, bind to device [%s]", inet_ntoa(serveraddr.sin_addr), SERVPORT, m_szEthInterf);
	
	int optval=1;
	int optlen=sizeof(optval);
	
	if ( setsockopt(sd , SOL_SOCKET, SO_BROADCAST, (char *)&optval,optlen) == SOCKET_ERROR )
	{
		LOG( "AllowBroadcast() %s", strerror(errno));
		close(sd);
		return -1;
	}
	
	LOG("UDP server - Listening...");
	while( !IsStop() )	
	{
		memset(bufptr, 0, buflen);
		
		while( !checkRecv( sd, 1000000 ) ) // wait 1 second - long enough to keep the processor loat at a low level
		{	//stay in loop waiting a message. This is necessary in order to check for IsStop
			if( IsStop() )
			{
				LOG("udpServer: STOP requested, terminate");
				close(sd);
				return 1;
			}
		}
		
		if((rc = recvfrom(sd, bufptr, buflen, 0, (struct sockaddr *)&clientaddr, (socklen_t *) &clientaddrlen))<0)
		{
			LOG("UDP Server - recvfrom() error %s", strerror(errno));
			continue;
		}
		
		LOG("Incomming message from %s:%d", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port) );
		
		if( !processData(bufptr, clientaddr) )
		{
			continue;
		}
		
		clientaddr.sin_family = AF_INET;
		clientaddr.sin_port = htons(SERVPORT);
		clientaddr.sin_addr.s_addr=INADDR_BROADCAST;

		usleep((rand()%10)*1000);
		LOG("Sendback DISCOVERY_REPLY");

		if((rc = sendto(sd, (const void*)&m_stDiscoveryResponse, sizeof(DiscoveryResponse_Msg), 0, (struct sockaddr *)&clientaddr, clientaddrlen))<0)
		{
			LOG("ERROR sendto() %s", strerror(errno));
			continue;
		}
	} 
	close(sd);
	return 1;
}