static void *
dispatch (void *arg)
{
  // every thread must register the same stream to write to file
  if (out_stream)
    {
      ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
      ACE_LOG_MSG->msg_ostream (out_stream);
    }

  ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (%t) Dispatcher Thread started!\n")));
  ACE_Reactor *r = reinterpret_cast <ACE_Reactor *> (arg);
  int result;

  r->owner (ACE_OS::thr_self ());

  while (1)
    {
      result = r->handle_events ();

      if (result <= 0)
        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("Dispatch: handle_events (): %d"),
                    result));
    }

  ACE_NOTREACHED (return 0);
}
Esempio n. 2
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  ACE_Sig_Action sa ((ACE_SignalHandler) handler, SIGINT);
  ACE_OS::signal (SIGCLD, SIG_IGN);
  ACE_UNUSED_ARG (sa);

  parse_args (argc, argv);

  OUTPUT_FILE = ACE_OS::open (OUTPUT_FILE_NAME, O_CREAT | O_WRONLY, 0644);
  if (OUTPUT_FILE == 0)
    return 1;

  ACE_Reactor reactor;
  Handle_Events handle_events (UDP_PORT, MCAST_ADDR, INTERFACE, reactor);

  // main loop

  while (!done)
    reactor.handle_events ();

  ACE_OS::close (OUTPUT_FILE);
  cout << "\nbenchd done.\n";
  return 0;
}
Esempio n. 3
0
// server main function
// uses a portable form of the "main" function along with its arguments
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{ 

  // instantiate an object of the Proto Handler class
  Proto_Handler proto;

  // retrieve a reactor. Here we could have retrieved different
  // implementations of reactor. For now we get the default singletom
  // reactor. 
  ACE_Reactor *reactor = ACE_Reactor::instance ();

  // initialize the proto handler object
  if (proto.open (argc, argv, reactor) == -1) {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) %p\n"), 
                  ACE_TEXT ("handler open")));
      return -1;
  }

  // now let the server handle the events
  for (;;) {
    if (reactor->handle_events () == -1) {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) %p\n"), 
                  ACE_TEXT ("handle events")));
      return -1;
    }
  }

  // return exit status
  return 0;
}
Esempio n. 4
0
static void *
worker (void *args)
{
  ACE_Reactor *reactor = reinterpret_cast<ACE_Reactor *> (args);

  // Make this thread the owner of the Reactor's event loop.
  reactor->owner (ACE_Thread::self ());

  // Use a timeout to inform the Reactor when to shutdown.
  ACE_Time_Value timeout (4);

  for (;;)
    switch (reactor->handle_events (timeout))
      {
      case -1:
        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("(%t) %p\n"),
                           ACE_TEXT ("reactor")),
                          0);
        /* NOTREACHED */
      case 0:
        ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Reactor shutdown\n")));
        return 0;
      }

  ACE_NOTREACHED (return 0);
}
Esempio n. 5
0
// This is run at program initialization
void CommandLineServer::run(void* args)
{
	s_log = log4cxx::Logger::getLogger("interface.commandlineserver");

	unsigned short tcpPort = (unsigned short)(unsigned long)args;
	//unsigned short tcpPort = (unsigned short)*(int*)args;

	CommandLineAcceptor peer_acceptor;
	ACE_INET_Addr addr (tcpPort);
	ACE_Reactor reactor;
	CStdString tcpPortString = IntToString(tcpPort);

	if (peer_acceptor.open (addr, &reactor) == -1)
	{
		LOG4CXX_ERROR(s_log, CStdString("Failed to start command line server on port:") + tcpPortString + CStdString(" do you have another instance of orkaudio running?"));
	}
	else
	{
		LOG4CXX_INFO(s_log, CStdString("Started command line server on port:")+tcpPortString);
		for(;;)
		{
			reactor.handle_events();
		}
	}
}
Esempio n. 6
0
int
main (int, char *[])
{
  // Instantiate a server which will receive messages for DURATION
  // seconds.
  Server_Events server_events (UDP_PORT,
                               MCAST_ADDR,
                               DURATION);
  // Instance of the ACE_Reactor.
  ACE_Reactor reactor;

  if (reactor.register_handler (&server_events,
                                ACE_Event_Handler::READ_MASK) == -1)
    ACE_ERROR ((LM_ERROR,
                "%p\n%a",
                "register_handler",
                1));

  ACE_DEBUG ((LM_DEBUG,
              "starting up server\n"));

  for (;;)
    reactor.handle_events (server_events.wait_time ());

  ACE_NOTREACHED (return 0;)
}
Esempio n. 7
0
static void *
worker (void *args)
{
  ACE_Reactor *reactor = (ACE_Reactor *) args;

  reactor->owner (ACE_Thread::self ());

  ACE_Time_Value timeout (4);

  for (;;)
    {
      //ACE_DEBUG ((LM_DEBUG, "(%t) calling handle_events\n"));

      switch (reactor->handle_events (timeout))
	{
	case -1:
	  ACE_ERROR_RETURN ((LM_ERROR, "(%t) %p\n", "reactor"), 0);
	  /* NOTREACHED */
	case 0:
	  ACE_ERROR_RETURN ((LM_ERROR, "(%t) timeout\n"), 0);
	  /* NOTREACHED */
	}

      // ACE_DEBUG ((LM_DEBUG, "(%t) done with handle_events\n"));

    }

  ACE_NOTREACHED(return 0);
}
Esempio n. 8
0
int MyTask::svc()
{
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("(%t) enter MyTask::svc()\n\n")));

    //initialization
    selector = new ACE_Select_Reactor;
    ACE_Reactor* reactor = new ACE_Reactor(selector);
    ACE_Reactor::instance(reactor);  //then, ACE_Reactor::instance() is reactor
    this->reactor(reactor);  //this reactor_ of ACE_Event_Handler can not be set

    //register socket handler
    Handler handler(UDP_PORT);
    if (reactor->register_handler(&handler, ACE_Event_Handler::READ_MASK) == -1)
    {
        ACE_ERROR((LM_ERROR, "%p\n", "cant't register with Reactor in MyTask::svc()\n"));
        return -1;
    }

    //spawn mytask2
    mytask2::instance()->open(&handler);

    //handle_events in forever-loop until receive two data packets from socket, then, it will notify the MY_EXIT_HANDLER
    while (exit_flag == 0)
    {
        int result = reactor->handle_events();  //timeout will not occur at all
        if (result)
        {
            ACE_DEBUG ((LM_INFO, ACE_TEXT ("(%t) handle_events() succeed, result = %d\n\n"), result));
            if (RECV_COUNT == handler.get_count())
            {
                ACE_DEBUG ((LM_INFO, ACE_TEXT ("(%t) MyTask::svc() notify the exit handler\n")));
                ACE_Reactor::instance()->notify(&handler, ACE_Event_Handler::EXCEPT_MASK);
            }

            if (handler.get_flag())
                exit_flag = 1;
        }
        else
        {
            ACE_ERROR((LM_ERROR, "%p\n", "handle_events() failed\n"));
            return -1;
        }
    }

    if (reactor->remove_handler(&handler, ACE_Event_Handler::READ_MASK |
                                ACE_Event_Handler::DONT_CALL) == -1)
    {
        ACE_ERROR((LM_ERROR, "%p\n", "cant't remove handler from Reactor\n"));
        return -1;
    }

    delete reactor;
    reactor = NULL;
    ACE_DEBUG ((LM_INFO, ACE_TEXT ("(%t) exit MyTask::svc()\n\n")));
    return 0;
}
int
handle_events (ACE_Reactor & reactor,
               bool & okay_to_close)
{
    ACE_Time_Value timeout (2);

    // Only one event handler should have been dispatched.
    if (reactor.handle_events (&timeout) != 1)
    {
        ACE_ERROR ((LM_ERROR,
                    ACE_TEXT ("Initial event dispatch failed\n")));
    }
    else
    {
        okay_to_close = true;

        // Run the event loop again in an attempt to make the reactor
        // dispatch the newly registered event handler.  No events
        // should be dispatched.
        timeout.sec (2);
        int const result = reactor.handle_events (&timeout);


        if (result > 0)
        {
            ACE_ERROR ((LM_ERROR,
                        ACE_TEXT ("Unexpectedly dispatched an event\n")));
        }
        else if (result < 0)
        {
            overall_result = -1;

            ACE_ERROR ((LM_ERROR,
                        ACE_TEXT ("Event loop failed unexpectedly\n")));
        }
        else
            return 0;
    }

    return -1;
}
Esempio n. 10
0
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  ACE_Reactor reactor;
  Event_Handler handler (reactor);

  int result = 0;
  while (result != -1)
    result = reactor.handle_events ();

  return 0;
}
Esempio n. 11
0
int
main (int, char *[])
{
  ACE_Reactor reactor;
  Event_Handler handler (reactor);

  int result = ACE_OS::thr_create ((ACE_THR_FUNC) worker, &handler, 0, 0);
  ACE_ASSERT (result == 0);

  for (result = 0; result != -1; result = reactor.handle_events ())
    continue;

  return 0;
}
Esempio n. 12
0
int
main (int, char **)
{
	char	addatapath[256];
	ctgList	url2ctg;
	init_env();

	// Create the acceptor that will listen for client connetions
	HarvestAcceptor peer_acceptor;

	StrUtil::path_merge(addatapath, adhome, "data");
	htmlTagEntity::init(addatapath);
	dbStore::prepare(
		config.GetStrVal("DBNAME", "ANYDICT"),
		config.GetStrVal("DBID", "inisoft"),
		config.GetStrVal("DBPASS", "gksehf"));

	/*
	ctgcnt = url2ctg.load();
	ACE_DEBUG ((LM_INFO,	"Ctg Prefix: %d\n", ctgcnt));
	url2ctg.print();
	*/
	categoryMapper::prepare();

	if (peer_acceptor.open (ACE_INET_Addr (PORT),
		&reactor) == -1)
		ACE_ERROR_RETURN ((LM_ERROR,
			"%p\n",
			"open"),
			-1);

	ACE_Sig_Action sa ((ACE_SignalHandler) handler, SIGINT);


	myCron mycron;
	mycron.activate();


	// Perform  service until the signal handler receives SIGINT.
	while (!finished)
		reactor.handle_events ();

	// Close the acceptor so that no more clients will be taken in.
	peer_acceptor.close();

	dbStore::finish();

	ACE_DEBUG ((LM_SHUTDOWN, "[%T] -- SHUT DOWN --\n"));
	return 0;
}
Esempio n. 13
0
int
ACE_TMAIN (int argc, ACE_TCHAR *[])
{
  // If argc > 1 then allow multiple handlers per-signal, else just
  // allow 1 handler per-signal.
  ACE_Sig_Handlers multi_handlers;

#if defined (ACE_WIN32)
  ACE_WFMO_Reactor reactor_impl (argc > 1
                                 ? &multi_handlers
                                 : (ACE_Sig_Handler *) 0);
#else
  ACE_Select_Reactor reactor_impl (argc > 1
                                   ? &multi_handlers
                                   : (ACE_Sig_Handler *) 0);
#endif /* ACE_WIN32 */
  ACE_Reactor reactor (&reactor_impl);

  if (argc > 1)
    {
      // Register an "external" signal handler so that the
      // ACE_Sig_Handlers code will have something to incorporate!

      ACE_SignalHandler eh = (ACE_SignalHandler) external_handler;
      ACE_Sig_Action sa (eh);

      sa.register_action (SIGINT);
    }

  // Create a bevy of handlers.
  Sig_Handler_1 h1 (reactor, "howdy");
  Sig_Handler_1 h2 (reactor, "doody");
  Sig_Handler_2 h3 (reactor, "tutty");
  Sig_Handler_2 h4 (reactor, "fruity");

  // Wait for user to type SIGINT and SIGQUIT.

  for (;;)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "\nwaiting for SIGINT or SIGQUIT\n"));

      if (reactor.handle_events () == -1)
        ACE_ERROR ((LM_ERROR,
                    "%p\n",
                    "handle_events"));
    }

  ACE_NOTREACHED (return 0);
}
Esempio n. 14
0
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  ACE_Reactor reactor;
  Event_Handler handler (reactor);

  int result = ACE_OS::thr_create ((ACE_THR_FUNC) worker, 0, 0, 0);
  ACE_TEST_ASSERT (result == 0);

  for (result = 0; result != -1; result = reactor.handle_events ())
    continue;

  return 0;
}
Esempio n. 15
0
int
main (int, char **)
{
	// Create the acceptor that will listen for client connetions
	ExtractAcceptor peer_acceptor;
	
	init_env();
	
	dbStore::prepare(
		config.GetStrVal("DBNAME", "ANYDICT"),
		config.GetStrVal("DBID", "inisoft"),
		config.GetStrVal("DBPASS", "gksehf"));

	EDict::prepare(adhome);

	TextProc::prepare();
	
	HDict::prepare(adhome);

	//unitTest();

	if (peer_acceptor.open (ACE_INET_Addr (PORT),
		&reactor) == -1)
		ACE_ERROR_RETURN ((LM_ERROR,
			"%p\n",
			"open"),
			-1);

	ACE_Sig_Action sa ((ACE_SignalHandler) handler, SIGINT);

	myCron mycron;
	mycron.activate();

	// Perform  service until the signal handler receives SIGINT.
	while (!finished)
		reactor.handle_events ();

	// Close the acceptor so that no more clients will be taken in.
	peer_acceptor.close();
	dbStore::finish();

	ACE_DEBUG ((LM_DEBUG,
		"[%T] -- SHUT DOWN --\n"));
	return 0;
}
Esempio n. 16
0
static void
run_svc (ACE_HANDLE handle)
{
  // The <callback> object is an <ACE_Event_Handler> created on the
  // stack.  This is normally not a good idea, but in this case it
  // works because the ACE_Reactor is destroyed before leaving this
  // scope as well, so it'll remove the <callback> object from its
  // internal tables BEFORE it is destroyed.
  Ping_Pong callback (string_name, handle);

  // Note that we put the <reactor> AFTER the <callback> so that the
  // <reactor> will get shutdown first.
  ACE_Reactor reactor;

  // Register the callback object for the various I/O, signal, and
  // timer-based events.

  if (reactor.register_handler (&callback,
				ACE_Event_Handler::READ_MASK
				| ACE_Event_Handler::WRITE_MASK) == -1
#if !defined (CHORUS)
      || reactor.register_handler (SIGINT,
                                   &callback) == -1
#endif /* CHORUS */
      || reactor.schedule_timer (&callback,
                                 0,
                                 SHUTDOWN_TIME) == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  "%p\n",
                  "reactor"));
      ACE_OS::exit (1);
    }

  // Main event loop (one per process).

  while (callback.is_set () == 0)
    if (reactor.handle_events () == -1)
      ACE_ERROR ((LM_ERROR,
                  "%p\n",
                  "handle_events"));
}
Esempio n. 17
0
int main (int, char* [])
{
    ACE_Reactor reactor;
    Time_Handler* th = new Time_Handler;
    int timer_id[NUMBER_TIMERS];
    for (int i = 0; i < NUMBER_TIMERS; i++)
	{
        timer_id[i] = reactor.schedule_timer(th,
                                              (const void *)i, // argument sent to handle_timeout()
                                              ACE_Time_Value(2 * i + 1)); //set timer to go off with delay
	}
	
    //Cancel the fifth timer before it goes off
    reactor.cancel_timer(timer_id[5]);//Timer ID of timer to be removed
    while (!done)
	{
        reactor.handle_events();
	}

    return 0;
}
Esempio n. 18
0
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  int result = reactor.register_handler (&simple_handler,
                                       simple_handler.event1_.handle ());
  ACE_ASSERT (result == 0);

  result = reactor.register_handler (&simple_handler,
                                     simple_handler.event2_.handle ());
  ACE_ASSERT (result == 0);

  result = ACE_OS::thr_create ((ACE_THR_FUNC) worker, 0, 0, 0);
  ACE_ASSERT (result == 0);

  result = 0;
  while (!stop_test && result != -1)
    {
      result = reactor.handle_events ();
    }
  return 0;
};
Esempio n. 19
0
bool
testit (ACE_Reactor_Impl *ri)
{
  int ret = 0;
  ACE_Reactor r (ri);
  ACE_Time_Value one (1);
  r.end_reactor_event_loop ();
  if ((ret = r.handle_events (one)) != -1)
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("Return value %d should be -1\n"), ret));
      return false;
    }
  if (errno != ESHUTDOWN)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("errno %d should be %d (ESHUTDOWN)\n"),
                  errno, ESHUTDOWN));
      return false;
    }

  return true;
}
Esempio n. 20
0
static void
run_svc (ACE_HANDLE handle)
{
  Ping_Pong *callback = 0;
  ACE_NEW (callback,
           Ping_Pong (ACE_TEXT_ALWAYS_CHAR (string_name),
                      handle));

  ACE_Reactor reactor;

  // Register the callback object for the various I/O, signal, and
  // timer-based events.

  if (reactor.register_handler (callback,
                                ACE_Event_Handler::READ_MASK
                                | ACE_Event_Handler::WRITE_MASK) == -1
#if !defined (CHORUS)
      || reactor.register_handler (SIGINT,
                                   callback) == -1
#endif /* CHORUS */
      || reactor.schedule_timer (callback,
                                 0,
                                 SHUTDOWN_TIME) == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("reactor")));
      ACE_OS::exit (1);
    }

  // Main event loop (one per process).

  while (callback->is_set () == 0)
    if (reactor.handle_events () == -1)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("handle_events")));
}
Esempio n. 21
0
int agent_impl::process_requests()
{
  ACE_TRACE("agent_impl::process_requests");
  ACE_Reactor reactor;

  ACE_Sig_Action sa ((ACE_SignalHandler) sig_handler, SIGINT);
  ACE_UNUSED_ARG (sa);

  // Read data from other side.
  if (reactor.register_handler (this, ACE_Event_Handler::READ_MASK) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, "ACE_Reactor::register_handler"), -1);

  // TODO: register signal handler to shut down gracefully here

  while (!finished)
    {
      reactor.handle_events ();
      ACE_DEBUG ((LM_DEBUG, "return from handle events\n"));
    }

  ACE_DEBUG ((LM_DEBUG, "return from handle events - normal shut down\n"));
  return 0;
}
Esempio n. 22
0
void EventStreamingServer::run(void* args)
{
	unsigned short tcpPort = (unsigned short)(ACE_UINT64)args;
	CStdString tcpPortString = IntToString(tcpPort);
	EventStreamingAcceptor peer_acceptor;
	ACE_INET_Addr addr (tcpPort);
	ACE_Reactor reactor;

	s_log = log4cxx::Logger::getLogger("interface.eventstreamingserver");

	if (peer_acceptor.open (addr, &reactor) == -1)
	{
		LOG4CXX_ERROR(s_log, CStdString("Failed to start event streaming server on port:") + tcpPortString + CStdString(" do you have another instance of orkaudio running?"));
	}
	else
	{
		LOG4CXX_INFO(s_log, CStdString("Started event streaming server on port:")+tcpPortString);
		for(;;)
		{
			reactor.handle_events();
		}
	}
}
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("Message_Queue_Notifications_Test"));

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("Starting message queue reactive notification test...\n")));

  ACE_Reactor reactor;
  Message_Handler mh (reactor);

  while (iterations > 0)
    reactor.handle_events ();

#if defined (ACE_HAS_THREADS)
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("Starting message queue watermark test...\n")));
  Watermark_Test watermark_test;
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("High water mark is %d\n")
              ACE_TEXT ("Low water mark is %d\n"),
              default_high_water_mark,
              default_low_water_mark));

  watermark_test.activate (THR_NEW_LWP,
                           worker_threads);

  ACE_Thread_Manager::instance ()->wait ();
#else
  ACE_DEBUG ((LM_INFO,
              ACE_TEXT ("Message queue watermark test not performed because threads are not supported\n")));
#endif /* ACE_HAS_THREADS */

  ACE_END_TEST;
  return 0;
}
// implement state machine, send, wait (timeout/results) return
int transaction::run()
{
  int rc, done = 0;
  int retry_counter = 0;
  ACE_Time_Value to(params_.get_timeout(), 0); // seconds
  ACE_Reactor *reactor = ACE_Reactor::instance ();

  // 1. register io port for read access
  if (reactor->register_handler(session_.get_handle(), this,
                                ACE_Event_Handler::READ_MASK) == -1)
    return SNMP_CLASS_INTERNAL_ERROR;

  // register a time handler and a socket with this

  while (!done) {

    if ((rc = send()) < 0)      // send pkt to agent
        return rc;
    else {
      if (retry_counter++ > params_.get_retry())
        return SNMP_CLASS_TIMEOUT;
    }

    // 2. wait for events (timeout, returned msg)
    if (( rc = reactor->handle_events (to)) == 1) // one handler registered
      return 0;
    else {
      if (rc == 0) {
         to.set(params_.get_timeout(), 0);
      }
      else
        return SNMP_CLASS_INTERNAL_ERROR;
    }
   }
  return SNMP_CLASS_INTERNAL_ERROR;
}
Esempio n. 25
0
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("MT_Reactor_Timer_Test"));

  int status = 0;
  int test_result = 0;

  ACE_Reactor *r = ACE_Reactor::instance ();

  Dispatch_Count_Handler callback;

  for (int i = ACE_MAX_TIMERS; i > 0; i--)
    // Schedule a timeout to expire immediately.
    if (r->schedule_timer (&callback,
                           reinterpret_cast <const void *> (static_cast <size_t> (i)),
                           ACE_Time_Value (0)) == -1)
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("%p\n"),
                         ACE_TEXT ("schedule_timer")),
                        1);

  ACE_Time_Value no_waiting (0);
  size_t events = 0;

  while (1)
    {
      int result = r->handle_events (no_waiting);

      // Timeout.
      if (result == 0)
        break;

      // Make sure there were no errors.
      ACE_TEST_ASSERT (result != -1);

      events += result;
    }

  // All <ACE_MAX_TIMERS> + 2 I/O dispatches (one for <handle_input>
  // and the other for <handle_exception>) should be counted in
  // events.
  if (events < ACE_MAX_TIMERS + 2)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("expected %d events, got %d instead\n"),
                  ACE_MAX_TIMERS + 2,
                  events));
    }

  status = callback.verify_results ();
  if (status != 0)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Dispatch counting test failed.\n")));
      test_result = 1;
    }

#if defined (ACE_HAS_THREADS)

  Time_Handler other_thread;
  ACE_Time_Value time_limit (30);

  // Set up initial set of timers.
  other_thread.setup ();

  other_thread.activate (THR_NEW_LWP | THR_JOINABLE);
  status = ACE_Reactor::instance()->run_reactor_event_loop (time_limit);
  // Should have returned only because the time limit is up...
  ACE_TEST_ASSERT (status != -1);
  ACE_TEST_ASSERT (time_limit.sec () == 0);

  status = other_thread.wait ();
  if (status == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p, errno is %d\n"),
                  "wait ()",
                  ACE_ERRNO_GET));
      ACE_TEST_ASSERT (status != -1);
    }

  status = other_thread.verify_results ();
  if (status != 0)
    test_result = 1;

#else
  ACE_ERROR ((LM_INFO,
              ACE_TEXT ("threads not supported on this platform\n")));
#endif /* ACE_HAS_THREADS */

  ACE_END_TEST;
  return test_result;
}
Esempio n. 26
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  if (parse_args (argc, argv) == -1)
    return -1;

  ACE_Select_Reactor sr;

  ACE_Reactor reac (&sr);

  ACE_Reactor::instance (&reac);

  ACE_SOCK_Stream stream[iter];

  ACE_SOCK_Connector connector[iter];

  Purging_Handler ph[iter];

  ACE_INET_Addr addr (port,
                      host);


  ACE_Reactor *singleton =
    ACE_Reactor::instance ();

  for (int i = 0; i != iter; ++i)
    {
      if (connector[i].connect (stream[i],
                                addr) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Error while connecting: %p\n",
                           "client"),
                          -1);

      if (stream[i].get_handle () == ACE_INVALID_HANDLE)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Got invalid handles after connecting the [%d] time\n",i),
                          -1);
      if (singleton->register_handler (stream[i].get_handle (),
                                       &ph[i],
                                       ACE_Event_Handler::READ_MASK) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Registration failed\n"),
                          -1);

      // ACE_Time_Value tv (1);

      // while (singleton->handle_events (&tv) >= 1);

    }

  // Handle events moved to here to prevent this test taking best part
  // of a minute
  ACE_Time_Value tv (3);

  while (singleton->handle_events (&tv) >= 1)
    {
      // No action.
    }

  // Remove the handlers to avoid the possibility of the reactor
  // using any of them after they leave the scope (those that haven't
  // been closed and removed already, that is).
  for (int j = 0; j != iter; ++j)
    {
      singleton->remove_handler (stream[j].get_handle (),
                                 ACE_Event_Handler::READ_MASK);
    }

  if ((iter - purged_handles) > 20)
    ACE_ERROR_RETURN ((LM_ERROR,
                      "(%P|%t) Purging hasnt worked at all\n"),
                       -1);

  return 0;
}
Esempio n. 27
0
int main(int argc, char** argv)
{ 
  bool analysisMode = false;
  MFileOperations f;
  char path[256];

  f.expandPath(path, "MESA_TARGET", "logs");
  MString logDir(path);
  f.expandPath(path, "MESA_STORAGE", "ordplc");
  MString storageDir(path);
  f.expandPath(path, "MESA_TARGET", "runtime");
  strcat(path, "/");
  MString hl7Base(path);

  MString hl7Definition(".ihe");
  MString databaseName("ordplc");
  MString returnMsgQueue("ORC");
  MString startEntityID("00000");
  MString defaultApplID("MESA_ORDPLC");
  MLogClient::LOGLEVEL logLevel = MLogClient::MLOG_NONE;
  int verbose = 0;
  int capture = 0;

  while (--argc > 0 && (*++argv)[0] == '-') {
    int l1 = 0;
    switch(*(argv[0] + 1)) {
    case 'a':
      analysisMode = true;
      break;
    case 'b':
      argc--; argv++;
      if (argc < 1)
	usage();
      hl7Base = MString(*argv) + "/";
      break;
    case 'd':
      argc--; argv++;
      if (argc < 1)
	usage();
      hl7Definition = MString(".") + *argv;
      break;
    case 'l':
      argc--;
      argv++;
      if (argc < 1)
	usage();
      if (sscanf(*argv, "%d", &l1) != 1)
	usage();
      logLevel = (MLogClient::LOGLEVEL)l1;
      break;
    case 's':
      argc--; argv++;
      if (argc < 1)
	usage();
      logDir = MString(*argv) + "/";
      break;
    case 'v':
      verbose++;
      break;
    case 'w':
      capture++;
      break;
    case 'z':
      argc--; argv++;
      if (argc < 1)
	usage();
      databaseName = *argv;
      break;
    default:
      break;
    }
  }
  if (argc < 1)
    usage();

  f.createDirectory(logDir);
  f.createDirectory(storageDir);

  if (logLevel != MLogClient::MLOG_NONE) {

    MLogClient logClient;
    logClient.initialize(logLevel, logDir + "/op_hl7ps.log");

    logClient.log(MLogClient::MLOG_VERBOSE,
	          "<no peer>", "op_hl7ps<main>", __LINE__,
	          "Begin server process");
    cerr << "op_hl7ps logging messages at level "
	 << logLevel
	 << " to "
	 << logDir + "/op_hl7ps.log"
	 << endl;
  }

  int port = atoi(*argv);

  //Write PID file
  MServerAgent a("op_hl7ps");
  a.registerServerPID();

  ACE_Reactor reactor;
  MHL7Factory factory(hl7Base, hl7Definition);
  MDBOrderPlacer orderPlacerDB (databaseName);
  MLMessenger* messenger;
#if 0
  if (analysisMode)
    messenger = new MAMessenger(factory, orderPlacerDB, logDir);
  else
    messenger = new MLMessenger (factory, orderPlacerDB, hl7Base+returnMsgQueue,
                                 startEntityID, defaultApplID);
//  messenger = new MLMessenger (factory, orderPlacerDB);
#endif
  int shutdownFlag = 0;
  messenger = new MLMessenger (factory, orderPlacerDB, hl7Base+returnMsgQueue,
                                 startEntityID, defaultApplID,
				logDir, storageDir, analysisMode, shutdownFlag);

  MHL7LLPHandler handler (*messenger);
  MHL7Acceptor acceptor (*messenger, handler);
  if (verbose)
    handler.verbose(1);

  handler.captureInputStream(capture);

  //Setup signal handler
  ACE_Sig_Action action ((ACE_SignalHandler) signalAction, SIGINT);
  if (acceptor.open (ACE_INET_Addr(port), &reactor) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
		       "%p\n",
		       " open"),
		      -1);

  ACE_DEBUG ((LM_DEBUG,
	      "(%P|%t) Firing up the Order Placer personality server on port %d\n", 
	      port));
  // Tell reactor to listen for messages:

  while (!finished) {
    reactor.handle_events();
    if (shutdownFlag != 0)
      break;
  }

  //We have been closed by a ^C signal.

  ACE_DEBUG ((LM_DEBUG,
    "(%P|%t) Shutting down the Order Placer personality server\n"));

  
//   clock = time(0);
//   ctime_r(&clock, timeStr, 32);
//   pidfile.open(name, ios::app|ios::out);
//   pidfile << "Finished: " << timeStr;
//   pidfile.close();
  a.closeServerPID();

  delete messenger;
  return 0;
}
Esempio n. 28
0
static int
run_notify_purge_test (void)
{
  int status;
  ACE_Reactor *r = ACE_Reactor::instance ();
  {
    Purged_Notify n1;
    Purged_Notify *n2;

    ACE_NEW_RETURN (n2, Purged_Notify, -1);
    auto_ptr<Purged_Notify> ap (n2);

    // First test:
    // Notify EXCEPT, and purge ALL
    r->notify (&n1); // the mask is EXCEPT_MASK

    status = r->purge_pending_notifications (&n1);
    if (status == -1 && errno == ENOTSUP)
      return 0;         // Select Reactor w/o ACE_HAS_REACTOR_NOTIFICATION_QUEUE
    if (status != 1)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 1\n"),
                  status));
    // Second test:
    // Notify READ twice, and WRITE once, and purge READ and WRITE - should purge 3 times.
    r->notify (&n1, ACE_Event_Handler::READ_MASK);
    r->notify (&n1, ACE_Event_Handler::READ_MASK);
    r->notify (&n1, ACE_Event_Handler::WRITE_MASK);
    status = r->purge_pending_notifications
      (&n1, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK);
    if (status != 3)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 3\n"),
                  status));
    // Third test:
    // Notify READ on 2 handlers, and purge READ|WRITE on all handlers. Should purge 2
    r->notify (&n1, ACE_Event_Handler::READ_MASK);
    r->notify (n2, ACE_Event_Handler::READ_MASK);
    status = r->purge_pending_notifications
      (0, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK);
    if (status != 2)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 2\n"),
                  status));
    // Forth test:
    // Notify EXCEPT and WRITE, purge READ. Should not purge
    r->notify (&n1); // the mask is EXCEPT_MASK
    r->notify (&n1, ACE_Event_Handler::WRITE_MASK);
    status = r->purge_pending_notifications
      (&n1, ACE_Event_Handler::READ_MASK);
    if (status != 0)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Purged %d notifies; expected 0\n"),
                  status));
    // Fifth test:
    r->notify (n2);

    // The destructor of the event handler no longer removes the
    // notifications.  It is the application's responsability to do
    // so.
    r->purge_pending_notifications(n2,
                                   ACE_Event_Handler::ALL_EVENTS_MASK);
    r->purge_pending_notifications(&n1,
                                   ACE_Event_Handler::ALL_EVENTS_MASK);
  }

  ACE_Time_Value t (1);
  status = r->handle_events (t);  // Should be nothing to do, and time out
  return status < 0 ? 1 : 0;     // Return 0 for all ok, else error
}
Esempio n. 29
0
int
TAO_Leader_Follower::wait_for_event (TAO_LF_Event *event,
                                     TAO_Transport *transport,
                                     ACE_Time_Value *max_wait_time)
{
  // Obtain the lock.
  ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, ace_mon, this->lock (), -1);

  TAO::ORB_Countdown_Time countdown (max_wait_time);

  // Optimize the first iteration [no access to errno]
  int result = 1;

  // For some cases the transport may disappear like when waiting for
  // connection to be initiated or closed. So cache the id.
  // @@ NOTE: This is not completely safe either. We will be fine for
  // cases that don't access the id ie. when debug level is off but
  // with debugging level on we are on a sticky wicket. Hopefully none
  // of our users should run TAO with debugging enabled like they did
  // in PathFinder
  size_t t_id = 0;

  if (TAO_debug_level && transport != 0)
  {
    t_id = transport->id ();
  }

  { // Scope #1: All threads inside here are client threads
    // Calls this->set_client_thread () on construction and
    // this->reset_client_thread () on destruction.
    TAO_LF_Client_Thread_Helper client_thread_helper (*this);
    ACE_UNUSED_ARG (client_thread_helper);

    // The loop here is for when we get elected (client) leader and
    // then later relinquish the leader position and our event has
    // still not completed (and we haven't run out of time).
    // All the conditions below are basically the various ways the
    // leader loop below can end, other than the event being complete
    while (event->keep_waiting_i ()
           && !(result == 0 &&
                max_wait_time != 0 &&
                *max_wait_time == ACE_Time_Value::zero)
           && result != -1)
    { // Scope #2: threads here alternate between being leader/followers

      // Check if there is a leader.  Note that it cannot be us since we
      // gave up our leadership when we became a client.
      if (this->leader_available ())
      { // Scope #3: threads here are followers
        // = Wait as a follower.

        // Grab a follower:
        TAO_LF_Follower_Auto_Ptr follower (*this);
        if (follower.get () == 0)
          return -1;

        if (TAO_debug_level >= 5)
          TAOLIB_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                      ACE_TEXT (" (follower), cond <%@>\n"),
                      t_id, follower.get ()));

        // Bound the follower and the LF_Event, this is important to
        // get a signal when the event terminates
        TAO_LF_Event_Binder event_binder (event, follower.get ());

        while (event->keep_waiting_i () &&
               this->leader_available ())
        { // Scope #4: this loop handles spurious wake-ups
          // Add ourselves to the list, do it everytime we wake up
          // from the CV loop. Because:
          //
          // - The leader thread could have elected us as the new
          // leader.
          // - Before we can assume the role another thread becomes
          // the leader
          // - But our condition variable could have been removed
          // already, if we don't add it again we will never wake
          // up.
          //
          // Notice that we can have spurious wake ups, in that case
          // adding the leader results in an error, that must be
          // ignored.
          // You may be thinking of not removing the condition
          // variable in the code that sends the signal, but
          // removing it here, that does not work either, in that
          // case the condition variable may be used twice:
          //
          //  - Wake up because its reply arrived
          //  - Wake up because it must become the leader
          //
          // but only the first one has any effect, so the leader is
          // lost.
          TAO_LF_Follower_Auto_Adder auto_adder (*this, follower);

          if (max_wait_time == 0)
          {
            if (follower->wait (max_wait_time) == -1)
              {
                if (TAO_debug_level >= 5)
                  TAOLIB_DEBUG ((LM_DEBUG,
                              ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event, ")
                              ACE_TEXT (" (follower) [no timer, cond failed]\n"),
                              t_id));

                // @@ Michael: What is our error handling in this case?
                //             We could be elected as leader and
                //             no leader would come in?
                return -1;
              }
          }
          else
          {
            countdown.update ();
            ACE_Time_Value tv = ACE_OS::gettimeofday ();
            tv += *max_wait_time;
            if (follower->wait (&tv) == -1)
              {
                if (TAO_debug_level >= 5)
                  TAOLIB_DEBUG ((LM_DEBUG,
                              ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait, ")
                              ACE_TEXT ("(follower) [has timer, follower failed]\n"),
                              t_id ));

                // If we have timedout set the state in the
                // LF_Event. We call the non-locking,
                // no-signalling method on LF_Event.
                if (errno == ETIME)
                    // We have timedout
                    event->set_state (TAO_LF_Event::LFS_TIMEOUT);

                if (!event->successful_i ())
                {
                  // Remove follower can fail because either
                  // 1) the condition was satisfied (i.e. reply
                  //    received or queue drained), or
                  // 2) somebody elected us as leader, or
                  // 3) the connection got closed.
                  //
                  // Therefore:
                  // If remove_follower fails and the condition
                  // was not satisfied, we know that we got
                  // elected as a leader.
                  // But we got a timeout, so we cannot become
                  // the leader, therefore, we have to select a
                  // new leader.
                  //

                  if (this->elect_new_leader () == -1
                      && TAO_debug_level > 0)
                  {
                    TAOLIB_ERROR ((LM_ERROR,
                                ACE_TEXT("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event, ")
                                ACE_TEXT("elect_new_leader failed\n"),
                                t_id ));
                  }
                }


              return -1;
            }
          }
        } // End Scope #4: loop to handle spurious wakeups

        countdown.update ();

        // @@ Michael: This is an old comment why we do not want to
        //             remove the follower here.
        // We should not remove the follower here, we *must* remove it when
        // we signal it so the same condition is not signalled for
        // both wake up as a follower and as the next leader.

        if (TAO_debug_level >= 5)
          TAOLIB_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                      ACE_TEXT (" done (follower), successful %d\n"),
                      t_id,
                      event->successful_i ()));

        // Now somebody woke us up to become a leader or to handle our
        // input. We are already removed from the follower queue.

        if (event->successful_i ())
          return 0;

        if (event->error_detected_i ())
          return -1;

        // FALLTHROUGH
        // We only get here if we woke up but the reply is not
        // complete yet, time to assume the leader role....
        // i.e. ACE_ASSERT (event->successful () == 0);
      } // End Scope #3: we are no longer a follower

      // One last attempt to avoid becoming a client-leader
      // If there is a new_leader_generator attached, give it a chance to
      // create a leader thread before becoming a leader.
      if (this->avoid_client_leader_ && this->no_leaders_available())
        {
          if (TAO_debug_level >= 5)
            {
              TAOLIB_DEBUG ((LM_DEBUG,
                          ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event, ")
                          ACE_TEXT ("Would become client leader, ")
                          ACE_TEXT ("but generating new thread\n"),
                          t_id));
            }

          // Yield, providing the event thread some time to grab leadership
          ACE_GUARD_RETURN (ACE_Reverse_Lock<TAO_SYNCH_MUTEX>, rev_mon,
                            this->reverse_lock (), -1);
          ACE_OS::thr_yield ();
          continue;
        }
      else
        {
          if (TAO_debug_level >= 5)
            {
              TAOLIB_DEBUG ((LM_DEBUG,
                          ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event, ")
                          ACE_TEXT ("Becoming client leader.\n"),
                          t_id));
            }
        }
      // = Leader Code.

      // The only way to reach this point is if we must become the
      // leader, because there is no leader or we have to update to a
      // leader or we are doing nested upcalls in this case we do
      // increase the refcount on the leader in TAO_ORB_Core.

      // Calls this->set_client_leader_thread () on
      // construction and this->reset_client_leader_thread ()
      // on destruction.  Note that this may increase the refcount of
      // the leader.
      { // Scope #5: We are now the client-leader
        TAO_LF_Client_Leader_Thread_Helper client_leader_thread_helper (*this);
        ACE_UNUSED_ARG (client_leader_thread_helper);

        { // Scope #6: release the lock via a reverse lock
          ACE_GUARD_RETURN (ACE_Reverse_Lock<TAO_SYNCH_MUTEX>, rev_mon,
                            this->reverse_lock (), -1);

          // Become owner of the reactor.
          ACE_Reactor *reactor = this->reactor_;
          reactor->owner (ACE_Thread::self ());

          // Run the reactor event loop.
          if (TAO_debug_level >= 5)
            TAOLIB_DEBUG ((LM_DEBUG,
                        ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                        ACE_TEXT (" (leader) enter reactor event loop\n"),
                        t_id));

          // If we got our event, no need to run the event loop any
          // further.
          while (event->keep_waiting_i ())
          {
            // Run the event loop.
            result = reactor->handle_events (max_wait_time);

            // Did we timeout? If so, stop running the loop.
            if (result == 0 &&
                max_wait_time != 0 &&
                *max_wait_time == ACE_Time_Value::zero)
              break;

            // Other errors? If so, stop running the loop.
            if (result == -1)
              break;

            // Has an event loop thread become available to take over?
            // Yes, we are checking this without the lock, however, if
            // we get a false reading we'll just circle around and
            // become leader again...
            if (this->event_loop_threads_waiting_)
              break;
            // Did we give up leadership?
            if (!this->is_client_leader_thread ())
              break;
            // Otherwise, keep going...
          }

          if (TAO_debug_level >= 5)
            TAOLIB_DEBUG ((LM_DEBUG,
                        ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                        ACE_TEXT (" (leader) exit reactor event loop\n"),
                        t_id));
        } // End Scope #6: we should now hold the lock again

        // End artificial scope for auto_ptr like helpers calling:
        // this->reset_client_leader_thread ().

      } // End Scope #5: we are no longer a client-leader
      // We only get here if we were the client leader and either our
      // event completed or an event loop thread has become available to
      // become leader.

      // resume any deferred events before we switch to a new leader thread
      this->resume_events ();

      // Wake and yield to any event loop threads that may be waiting to
      // take leadership - otherwise we will just loop around and take
      // leadership again (because we hold the lock).
      if (this->event_loop_threads_waiting_ && !this->leader_available ())
      {
        if (TAO_debug_level >= 5)
          TAOLIB_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                      ACE_TEXT (" (client) waking and yielding to allow event thread leadership\n"),
                      t_id));

        // Wake up the next leader (in case not yet done)
        if (this->elect_new_leader () == -1)
          TAOLIB_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                             ACE_TEXT (" failed to elect new leader\n"),
                             t_id),
                            -1);

        // Yield, providing the event thread some time to grab leadership
        ACE_GUARD_RETURN (ACE_Reverse_Lock<TAO_SYNCH_MUTEX>, rev_mon,
                          this->reverse_lock (), -1);
        ACE_OS::thr_yield ();
      }

    } // End Scope #2: we loop here if our event is incomplete


  // End artificial scope for auto_ptr like helpers calling:
  // this->reset_client_thread ()

  // We should only get here when our event is complete or timed-out
  } // End Scope #1

  // Wake up the next leader, we cannot do that in handle_input,
  // because the woken up thread would try to get into handle_events,
  // which is at the time in handle_input still occupied. But do it
  // before checking the error in <result>, even if there is an error
  // in our input we should continue running the loop in another
  // thread.

  if (this->elect_new_leader () == -1)
    TAOLIB_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                       ACE_TEXT (" failed to elect new leader\n"),
                       t_id),
                      -1);

  if (result == -1 && !this->reactor_->reactor_event_loop_done ())
    TAOLIB_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("TAO (%P|%t) - Leader_Follower[%d]::wait_for_event,")
                       ACE_TEXT (" handle_events failed\n"),
                       t_id),
                      -1);

  // Return an error if there was a problem receiving the reply...
  if (max_wait_time != 0)
    {
      if (!event->successful_i ()
          && *max_wait_time == ACE_Time_Value::zero)
        {
          result = -1;
          errno = ETIME;
        }
      else if (event->error_detected_i ())
        {
          // If the time did not expire yet, but we get a failure,
          // e.g. the connections closed, we should still return an error.
          result = -1;
        }
    }
  else
    {
      /**
       * There should be no reason to reset the value of result
       * here. If there was an error in handle_events () that the
       * leader saw, I (Bala) believe it should be propagated to the
       * clients.
       * result = 0;
       */
      if (event->error_detected_i ())
        {
          result = -1;
        }
    }

  return result;
}