Example #1
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;)
}
int
ACE_Process_Manager::append_proc (ACE_Process *proc)
{
  ACE_TRACE ("ACE_Process_Manager::append_proc");

  // Try to resize the array to twice its existing size if we run out
  // of space...
  if (this->current_count_ >= this->max_process_table_size_
      && this->resize (this->max_process_table_size_ * 2) == -1)
    return -1;
  else
    {
      ACE_Process_Descriptor &proc_desc =
        this->process_table_[this->current_count_];

      proc_desc.process_ = proc;
      proc_desc.exit_notify_ = 0;

#if defined (ACE_WIN32)
      // If we have a Reactor, then we're supposed to reap Processes
      // automagically.  Get a handle to this new Process and tell the
      // Reactor we're interested in <handling_input> on it.

      ACE_Reactor *r = this->reactor ();
      if (r != 0)
        r->register_handler (this,
                             proc->gethandle ());
#endif /* ACE_WIN32 */

      this->current_count_++;
      return 0;
    }
}
Example #3
0
Handle_Events::Handle_Events (u_short udp_port,
			      const char *ip_addr,
			      const char *interface,
			      ACE_Reactor &reactor)
{
  // Create multicast address to listen on.

  ACE_INET_Addr sockmc_addr (udp_port, ip_addr);

  // subscribe to multicast group.

  if (this->mcast_.subscribe (sockmc_addr, 1, interface) == -1)
    ACE_OS::perror ("can't subscribe to multicast group"), ACE_OS::exit (1);

  // Disable loopbacks.
  //  if (this->mcast_.set_option (IP_MULTICAST_LOOP, 0) == -1 )
  //    ACE_OS::perror (" can't disable loopbacks " ), ACE_OS::exit (1);

  if (!QUIET) {
    this->handle_set_.set_bit (0);
  }
  this->handle_set_.set_bit (this->mcast_.get_handle ());

  // Register callbacks with the ACE_Reactor.
  if (reactor.register_handler (this->handle_set_,
				this,
				ACE_Event_Handler::READ_MASK) == -1)
    ACE_OS::perror ("can't register events"), ACE_OS::exit (1);
}
Dispatch_Count_Handler::Dispatch_Count_Handler (void)
{

  ACE_Reactor *r = ACE_Reactor::instance ();

  this->input_seen_ = this->notify_seen_ = 0;
  this->timers_fired_ = 0;

  // Initialize the pipe.
  if (this->pipe_.open () == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("ACE_Pipe::open")));
  // Register the "read" end of the pipe.
  else if (r->register_handler (this->pipe_.read_handle (),
                                this,
                                ACE_Event_Handler::READ_MASK) == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("register_handler")));
  // Put something in our pipe and smoke it... ;-)
  else if (ACE::send (this->pipe_.write_handle (),
                      "z",
                      1) == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("send")));
  // Call notify to prime the pump for this, as well.
  else if (r->notify (this) == -1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("notify")));
}
Example #5
0
int
Server_i::enable_multicast (const char *ior)
{
  if (this->parse_args (this->argc_, this->argv_) != 0)
    return -1;

  // Get reactor instance from TAO.
  ACE_Reactor *reactor =
    this->orb_->orb_core ()->reactor ();

  // Instantiate a handler which will handle client requests for the
  // bootstrappable service, received on the multicast port.
  ACE_NEW_RETURN (this->ior_multicast_,
                  TAO_IOR_Multicast (),
                  -1);

  if (this->ior_multicast_->init (ior,
                                  this->mcast_address_.in (),
                                  TAO_SERVICEID_MCASTSERVER) == -1)
    return -1;

  // Register event handler for the ior multicast.
  if (reactor->register_handler (this->ior_multicast_,
                                 ACE_Event_Handler::READ_MASK) == -1)
    {
      if (TAO_debug_level > 0)
        ACE_DEBUG ((LM_DEBUG,
                    "MCast_Server: cannot register Event handler\n"));
      return -1;
    }

  return 0;
}
Example #6
0
  Sig_Handler_1 (ACE_Reactor &reactor, const char *msg)
    : msg_ (msg),
      count_ (0),
      reactor_ (reactor)
  {
    // Register the signal handlers.
    this->quit_sigkey_ =
      reactor.register_handler (SIGQUIT, this);
    this->int_sigkey_ =
      reactor.register_handler (SIGINT, this);

    if (this->quit_sigkey_ == -1 || this->int_sigkey_ == -1)
      ACE_ERROR ((LM_ERROR,
                  "%p\n",
                  "register_handler"));
  }
Example #7
0
int HandlersRegister::registerDgramHandlers ()
{
  int i;

  // open dgram handlers for all ports
  for (i = 0; i < HandlersNo; ++i)
    if (-1 == DgramHandlers_[ i ]->open (
                                         ACE_INET_Addr (i + BaseDgramPort,
                                                        ACE_TEXT ("127.0.0.1"),
                                                        ACE_PROTOCOL_FAMILY_INET)))
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT (" (%P) %p\n"),
                         ACE_TEXT ("Cannot open dgram handler")),
                        -1);

  // register dgram handlers
  for (i = 0; i < HandlersNo; ++i)
    if (-1 == reactor_->register_handler (DgramHandlers_[ i ],
                                          ACE_Event_Handler::READ_MASK))
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT (" (%P) %p\n"),
                         ACE_TEXT ("Cannot register dgram handler")),
                        -1);
  return 0;
}
Example #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;
}
Example #9
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"));
}
Example #10
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;
};
Example #11
0
int
main (int argc, char**argv)
{
    // The worlds most useless user interface
    Widget top_level = XtVaAppInitialize (NULL,
                                          "buttontest",
                                          NULL,
                                          0,
                                          &argc,
                                          argv,
                                          NULL,
                                          NULL);
    Widget button = XmCreatePushButton (top_level,
                                        "change",
                                        0,
                                        0);
    XtManageChild (button);
    XtAddCallback (button,
                   XmNactivateCallback,
                   ActivateCB,
                   NULL);

    // A reactor beastie.
    ACE_XtReactor xreactor (XtWidgetToApplicationContext (top_level));
    ACE_Reactor reactor (&xreactor);

    // Print a message when data is recv'd on stdin...
    ACE_Event_Handler *stdin_;
    ACE_NEW_RETURN (stdin_,
                    Stdin (new Stdout (&reactor)),
                    -1);
    reactor.register_handler (stdin_,
                              ACE_Event_Handler::READ_MASK);

    // Print a message every 10 seconds.
    if (reactor.schedule_timer (stdin_, 0,
                                ACE_Time_Value (10),
                                ACE_Time_Value (10)) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "%p\n",
                           "schedule_timer"),
                          -1);

    // Show the top_level widget.
    XtRealizeWidget (top_level);

    // Demonstrate Reactor/Xt event loop unification.
    XtAppMainLoop (XtWidgetToApplicationContext (top_level));

    return 0;
}
Example #12
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")));
}
int
RtpsUdpReceiveStrategy::start_i()
{
  ACE_Reactor* reactor = link_->get_reactor();
  if (reactor == 0) {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: ")
                      ACE_TEXT("RtpsUdpReceiveStrategy::start_i: ")
                      ACE_TEXT("NULL reactor reference!\n")),
                     -1);
  }

  if (reactor->register_handler(link_->unicast_socket().get_handle(), this,
                                ACE_Event_Handler::READ_MASK) != 0) {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: ")
                      ACE_TEXT("RtpsUdpReceiveStrategy::start_i: ")
                      ACE_TEXT("failed to register handler for unicast ")
                      ACE_TEXT("socket %d\n"),
                      link_->unicast_socket().get_handle()),
                     -1);
  }

  if (link_->config()->use_multicast_) {
    if (reactor->register_handler(link_->multicast_socket().get_handle(), this,
                                  ACE_Event_Handler::READ_MASK) != 0) {
      ACE_ERROR_RETURN((LM_ERROR,
                        ACE_TEXT("(%P|%t) ERROR: ")
                        ACE_TEXT("RtpsUdpReceiveStrategy::start_i: ")
                        ACE_TEXT("failed to register handler for multicast\n")),
                       -1);
    }
  }

  return 0;
}
Example #14
0
int
Receiver::open (void *)
{
  ACE_Guard<ACE_Recursive_Thread_Mutex> locker (mutex_);

  ACE_Reactor *TPReactor = ACE_Reactor::instance ();

  this->reactor (TPReactor);

  flg_mask_ = ACE_Event_Handler::NULL_MASK ;

  if (TPReactor->register_handler (this, flg_mask_) == -1)
    return -1;

  initiate_io (ACE_Event_Handler::READ_MASK);

  return check_destroy ();
}
Example #15
0
int
TAO_Acceptor::handle_accept_error (ACE_Event_Handler* base_acceptor)
{
  if (errno == EMFILE || errno == ENFILE)
    {
      if (TAO_debug_level > 0)
        TAOLIB_DEBUG ((LM_DEBUG, "TAO (%P|%t) - "
                              "TAO_Acceptor::handle_accept_error - "
                              "Too many files open\n"));

      // If the user has decided to stop accepting when the file handles
      // run out, just return -1;
      if (this->error_retry_delay_ == 0)
        return -1;

      // Get the reactor.  If there isn't one, which isn't very likely,
      // then just return -1.
      ACE_Reactor* reactor = base_acceptor->reactor ();
      if (reactor == 0)
        return -1;

      // So that the reactor doesn't completely remove this handler from
      // the reactor, register it with the except mask.  It should be
      // removed in the timer handler.
      reactor->register_handler (base_acceptor,
                                 ACE_Event_Handler::EXCEPT_MASK);

      // Remove the handler so that the reactor doesn't attempt to
      // process this handle again (and tightly spin).
      reactor->remove_handler (base_acceptor,
                               ACE_Event_Handler::ACCEPT_MASK |
                               ACE_Event_Handler::DONT_CALL);

      // Schedule a timer so that we can resume the handler in hopes
      // that some file handles have freed up.
      ACE_Time_Value timeout (this->error_retry_delay_);
      reactor->schedule_timer (base_acceptor, 0, timeout);
    }

  // We want to keep accepting in all other situations.
  return 0;
}
Example #16
0
int Sender::open (void *)
{
  ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, locker, this->mutex_, -1);

  ACE_Reactor * TPReactor = ACE_Reactor::instance ();

  this->reactor (TPReactor);

  flg_mask_ = ACE_Event_Handler::NULL_MASK ;

  if (TPReactor->register_handler (this,flg_mask_) == -1)
    return -1;

  if (this->initiate_write () == -1)
    return -1;

  if (duplex != 0)
    initiate_io (ACE_Event_Handler::READ_MASK);

  return check_destroy ();
}
Example #17
0
int
UdpReceiveStrategy::start_i()
{
  ACE_Reactor* reactor = this->link_->get_reactor();
  if (reactor == 0) {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: ")
                      ACE_TEXT("UdpReceiveStrategy::start_i: ")
                      ACE_TEXT("NULL reactor reference!\n")),
                     -1);
  }

  if (reactor->register_handler(this, ACE_Event_Handler::READ_MASK) != 0) {
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: ")
                      ACE_TEXT("UdpReceiveStrategy::start_i: ")
                      ACE_TEXT("failed to register handler for DataLink!\n")),
                     -1);
  }

  return 0;
}
// implement state machine, send, wait (timeout/results) return
int transaction::run(transaction_result * r)
{
    result_ = r;
    int rc;

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

    retry_counter_ = 0;

    // register a time handler and a socket with this
    ACE_Time_Value to = params_.get_timeout();
    if (reactor->schedule_timer(this, 0, to, to) < 0)
        return SNMP_CLASS_INTERNAL_ERROR;

    if ((rc = send()) < 0)      // send pkt to agent
        return rc;
    return 0;
}
Example #19
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;
}
Example #20
0
int
TAO_Acceptor::handle_expiration (ACE_Event_Handler* base_acceptor)
{
  // Get the reactor.  If there isn't one, which isn't very likely, then
  // just return -1;
  ACE_Reactor* reactor = base_acceptor->reactor ();
  if (reactor == 0)
    return -1;

  if (TAO_debug_level > 0)
    TAOLIB_DEBUG ((LM_DEBUG, "TAO (%P|%t) - "
                          "TAO_Acceptor::handle_expiration - "
                          "Re-registering the acceptor\n"));

  // Try again to allow incoming connections
  reactor->register_handler (base_acceptor, ACE_Event_Handler::ACCEPT_MASK);

  // Remove the except mask that was added during the handling of the
  // accept() error.  That is the only reason that we're in this method
  // in the first place.
  reactor->remove_handler (base_acceptor, ACE_Event_Handler::EXCEPT_MASK |
                                          ACE_Event_Handler::DONT_CALL);
  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;
}
int main(int argc, char *argv[])
{
  int rc = 0;
  bool first = true;

  ImageVector v;

  Client client(argc, argv);

  if ((rc = parseArgs(argc, argv)))
    return rc;

  try {
    // event handler
    Event * event = new Event();
    
    // Signal set to be handled by the event handler.
    ACE_Sig_Set sig;
    
    // register Signal handler for Ctr+C
    sig.sig_add(SIGINT);
    sig.sig_add(SIGTERM);
    
    // Reactor, misused as signal handler
    ACE_Reactor reactor;
    
    if (reactor.register_handler(sig, event) == -1) {
      throw Miro::ACE_Exception(errno, "failed to register signal handler");
    }
    
    // get reference to video service
    Video_var video = client.resolveName<Video>(interfaceName.c_str());
    Miro::VideoConnection connection(video.in());

    ACE_Time_Value start;
    while(!canceled) {

      // wait for key
      if (first || !streaming) {
	first = false;
	cout << "Press key to grab next image: " << flush;
	getchar();
	start = ACE_OS::gettimeofday();
      }
    
      // init streaming timer
      if (!first && streaming) {
	ACE_Time_Value elapsed = ACE_OS::gettimeofday();
	elapsed -= start;
	if (elapsed.msec() > stop)
	  break;
      }

      {
	// get image
	Miro::VideoAcquireImage 
	  frame(connection, 
		(interval)?
		Miro::VideoAcquireImage::Current :
		Miro::VideoAcquireImage::Next);

	// fill image structure
	Image image;
	image.fileName = path() + client.namingContextName + "_" + Miro::timeString() + ".ppm";
	image.width = connection.handle->format.width;
	image.height = connection.handle->format.height;
	
	// fill image buffer
	if (!bgr && !streaming)
	  image.buffer = (char*) frame.buffer;
	else {
	  image.buffer = new char[3 * image.width * image.height];

	  // byte swapping
	  if (bgr) {
	    int offset = 0;
	    for (int i = 0; i < image.width; ++i) {
	      for (int j = 0; j < image.height; ++j, offset += 3) {
		image.buffer[offset + 0] = frame.buffer[offset + 2]; // r
		image.buffer[offset + 1] = frame.buffer[offset + 1]; // g
		image.buffer[offset + 2] = frame.buffer[offset + 0]; // b
	      }
	    }
	  }
	  else
	    memcpy(image.buffer, frame.buffer, 3 * image.width * image.height);
	}
	
	// save image
	if (!streaming) {
	  image.writePpm();
	  if (bgr)
	    delete[] image.buffer;
	}
	else 
	  v.push_back(image);
      }

      // sleep
      if (interval) {
	ACE_Time_Value delta;
	delta.msec(interval);
	ACE_OS::sleep(delta);
      }
    }
    cout << "exiting on signal" << endl;

    for (ImageVector::const_iterator i = v.begin(); i != v.end(); ++i) {
      i->writePpm();
      delete i->buffer;
    }
  }
  catch (const Miro::ETimeOut& e) {
    cerr << "Miro Timeout Exception: " << e << endl;
    rc = 1;
  }
  catch (const Miro::EDevIO & e) {
    cerr << "Miro Device I/O exception: " << e << endl;
    rc = 1;
  }
  catch (const Miro::EOutOfBounds & e) {
    cerr << "Miro out of bounds exception: " << e << endl;
    rc = 1;
  }
  catch (const CORBA::Exception & e) {
    cerr << "Uncaught CORBA exception: " << e << endl;
    rc = 1;
  }
  return rc;
}
Example #23
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;
}
Example #24
0
int
TAO_Naming_Server::init_new_naming (CORBA::ORB_ptr orb,
                                    PortableServer::POA_ptr poa,
                                    const ACE_TCHAR *persistence_location,
                                    void *base_addr,
                                    size_t context_size,
                                    int enable_multicast,
                                    int use_storable_context,
                                    int round_trip_timeout,
                                    int use_round_trip_timeout)
{
  try
    {
#if defined (CORBA_E_MICRO)
      ACE_UNUSED_ARG (persistence_location);
      ACE_UNUSED_ARG (base_addr);
      ACE_UNUSED_ARG (use_storable_context);
#else
      if (use_storable_context)
        {
          // In lieu of a fully implemented service configurator version
          // of this Reader and Writer, let's just take something off the
          // command line for now.
          TAO::Storable_Factory* pf = 0;
          ACE_CString directory (ACE_TEXT_ALWAYS_CHAR (persistence_location));
          ACE_NEW_RETURN (pf, TAO::Storable_FlatFileFactory (directory), -1);
          auto_ptr<TAO::Storable_Factory> persFactory(pf);

          // Use an auto_ptr to ensure that we clean up the factory in the case
          // of a failure in creating and registering the Activator.
          TAO_Storable_Naming_Context_Factory* cf =
            this->storable_naming_context_factory (context_size);
          // Make sure we got a factory
          if (cf == 0) return -1;
          auto_ptr<TAO_Storable_Naming_Context_Factory> contextFactory (cf);

          // This instance will either get deleted after recreate all or,
          // in the case of a servant activator's use, on destruction of the
          // activator.

          // Was a location specified?
          if (persistence_location == 0)
            {
              // No, assign the default location "NameService"
              persistence_location = ACE_TEXT ("NameService");
            }

          // Now make sure this directory exists
          if (ACE_OS::access (persistence_location, W_OK|X_OK))
            {
              ORBSVCS_ERROR_RETURN ((LM_ERROR, "Invalid persistence directory\n"), -1);
            }

#if (TAO_HAS_MINIMUM_POA == 0) && !defined (CORBA_E_COMPACT)
          if (this->use_servant_activator_)
            {
              ACE_NEW_THROW_EX (this->servant_activator_,
                                TAO_Storable_Naming_Context_Activator (orb,
                                                                       persFactory.get(),
                                                                       contextFactory.get (),
                                                                       persistence_location),
                                CORBA::NO_MEMORY ());
              this->ns_poa_->set_servant_manager(this->servant_activator_);
            }
#endif /* TAO_HAS_MINIMUM_POA */
          try {  // The following might throw an exception.
            this->naming_context_ =
              TAO_Storable_Naming_Context::recreate_all (orb,
              poa,
              TAO_ROOT_NAMING_CONTEXT,
              context_size,
              0,
              contextFactory.get (),
              persFactory.get (),
              use_redundancy_);
          }
          catch (const CORBA::Exception& ex)
          {
            // The activator already took over the factories so we need to release the auto_ptr
            if (this->use_servant_activator_)
            {
              // The context factory is now owned by the activator
              // so we should release it
              contextFactory.release ();
              // If using a servant activator, the activator now owns the
              // factory, so we should release it
              persFactory.release ();
            }
            // Print out the exception and return failure
            ex._tao_print_exception (
              "TAO_Naming_Server::init_new_naming");
            return -1;
          }

        // Kind of a duplicate of the above here, but we must also release the
        // factory autoptrs in the good case as well.
        if (this->use_servant_activator_)
            {
              // The context factory is now owned by the activator
              // so we should release it
              contextFactory.release ();
              // If using a servant activator, the activator now owns the
              // factory, so we should release it
              persFactory.release ();
            }

      }
      else if (persistence_location != 0)
        //
        // Initialize Persistent Naming Service.
        //
        {

          // Create Naming Context Implementation Factory to be used for the creation of
          // naming contexts by the TAO_Persistent_Context_Index
          TAO_Persistent_Naming_Context_Factory *naming_context_factory =
            this->persistent_naming_context_factory ();
          // Make sure we got a factory.
          if (naming_context_factory == 0) return -1;

          // Allocate and initialize Persistent Context Index.
          ACE_NEW_RETURN (this->context_index_,
                          TAO_Persistent_Context_Index (orb, poa, naming_context_factory),
                          -1);

          if (this->context_index_->open (persistence_location,
                                          base_addr) == -1
              || this->context_index_->init (context_size) == -1)
            {
              if (TAO_debug_level >0)
                ORBSVCS_DEBUG ((LM_DEBUG,
                            "TAO_Naming_Server: context_index initialization failed\n"));
              return -1;
            }

          // Set the root Naming Context reference.
          this->naming_context_ =
            this->context_index_->root_context ();
        }
      else
#endif /* CORBA_E_MICRO */
        {
          //
          // Initialize Transient Naming Service.
          //
          this->naming_context_ =
            TAO_Transient_Naming_Context::make_new_context (poa,
                                                            TAO_ROOT_NAMING_CONTEXT,
                                                            context_size);

        }

#if !defined (CORBA_E_MICRO)
      // Register with the ORB's resolve_initial_references()
      // mechanism.  Primarily useful for dynamically loaded Name
      // Services.
      orb->register_initial_reference ("NameService",
                                       this->naming_context_.in ());
#endif /* CORBA_E_MICRO */

      // Set the ior of the root Naming Context.
      this->naming_service_ior_=
        orb->object_to_string (this->naming_context_.in ());

      CORBA::Object_var table_object =
        orb->resolve_initial_references ("IORTable");

      IORTable::Table_var adapter =
        IORTable::Table::_narrow (table_object.in ());
      if (CORBA::is_nil (adapter.in ()))
        {
          ORBSVCS_ERROR ((LM_ERROR, "Nil IORTable\n"));
        }
      else
        {
          CORBA::String_var ior =
            orb->object_to_string (this->naming_context_.in ());
          adapter->bind ("NameService", ior.in ());
        }

#if defined (ACE_HAS_IP_MULTICAST)
      if (enable_multicast)
        {
          // @@ Marina: is there anyway to implement this stuff
          // without using ORB_Core_instance()? For example can you
          // pass the ORB as an argument?

          //
          // Install ior multicast handler.
          //
          // Get reactor instance from TAO.
          ACE_Reactor *reactor = orb->orb_core()->reactor ();

          // See if the -ORBMulticastDiscoveryEndpoint option was specified.
          ACE_CString mde (orb->orb_core ()->orb_params ()->mcast_discovery_endpoint ());

          // First, see if the user has given us a multicast port number
          // on the command-line;
          u_short port =
            orb->orb_core ()->orb_params ()->service_port (TAO::MCAST_NAMESERVICE);

          if (port == 0)
            {
              // Check environment var. for multicast port.
              const char *port_number =
                ACE_OS::getenv ("NameServicePort");

              if (port_number != 0)
                port = static_cast<u_short> (ACE_OS::atoi (port_number));
            }

          // Port wasn't specified on the command-line or in environment -
          // use the default.
          if (port == 0)
            port = TAO_DEFAULT_NAME_SERVER_REQUEST_PORT;

          // Instantiate a handler which will handle client requests for
          // the root Naming Context ior, received on the multicast port.
          ACE_NEW_RETURN (this->ior_multicast_,
                          TAO_IOR_Multicast (),
                          -1);

          if (mde.length () != 0)
            {
              if (this->ior_multicast_->init (this->naming_service_ior_.in (),
                                              mde.c_str (),
                                              TAO_SERVICEID_NAMESERVICE) == -1)
                return -1;
            }
          else
            {
              if (this->ior_multicast_->init (this->naming_service_ior_.in (),
                                              port,
#if defined (ACE_HAS_IPV6)
                                              ACE_DEFAULT_MULTICASTV6_ADDR,
#else
                                              ACE_DEFAULT_MULTICAST_ADDR,
#endif /* ACE_HAS_IPV6 */
                                              TAO_SERVICEID_NAMESERVICE) == -1)
                return -1;
            }

          // Register event handler for the ior multicast.
          if (reactor->register_handler (this->ior_multicast_,
                                         ACE_Event_Handler::READ_MASK) == -1)
            {
              if (TAO_debug_level > 0)
                ORBSVCS_DEBUG ((LM_DEBUG,
                            "TAO_Naming_Server: cannot register Event handler\n"));
              return -1;
            }

          if (TAO_debug_level > 0)
            ORBSVCS_DEBUG ((LM_DEBUG,
                        "TAO_Naming_Server: The multicast server setup is done.\n"));
        }
#else
  ACE_UNUSED_ARG (enable_multicast);
#endif /* ACE_HAS_IP_MULTICAST */

#if defined (TAO_HAS_CORBA_MESSAGING) && TAO_HAS_CORBA_MESSAGING != 0
      if (use_round_trip_timeout == 1)
      {
        TimeBase::TimeT roundTripTimeoutVal = round_trip_timeout;
        CORBA::Any anyObjectVal;
        anyObjectVal <<= roundTripTimeoutVal;
        CORBA::PolicyList polList (1);
        polList.length (1);
        polList[0] = orb->create_policy (Messaging::RELATIVE_RT_TIMEOUT_POLICY_TYPE,
                                         anyObjectVal);

        // set a timeout on the orb
        //
        CORBA::Object_var orbPolicyManagerObj =
          orb->resolve_initial_references ("ORBPolicyManager");

        CORBA::PolicyManager_var orbPolicyManager =
          CORBA::PolicyManager::_narrow (orbPolicyManagerObj.in ());
        orbPolicyManager->set_policy_overrides (polList, CORBA::SET_OVERRIDE);

        polList[0]->destroy ();
        polList[0] = CORBA::Policy::_nil ();
      }
#else
  ACE_UNUSED_ARG (use_round_trip_timeout);
  ACE_UNUSED_ARG (round_trip_timeout);
#endif /* TAO_HAS_CORBA_MESSAGING */
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception (
        "TAO_Naming_Server::init_new_naming");
      return -1;
    }

  return 0;
}
Example #25
0
int
TAO_Trading_Loader::init_multicast_server (void)
{
#if defined (ACE_HAS_IP_MULTICAST)
  // Get reactor instance from TAO.
  ACE_Reactor *reactor = TAO_ORB_Core_instance ()->reactor ();

  // See if the -ORBMulticastDiscoveryEndpoint option was specified.
  ACE_CString mde (TAO_ORB_Core_instance ()->orb_params ()
                   ->mcast_discovery_endpoint ());

  // First, see if the user has given us a multicast port number for
  // the name service on the command-line;
  u_short port =
    TAO_ORB_Core_instance ()->orb_params ()->service_port (TAO::MCAST_TRADINGSERVICE);

  if (port == 0)
    {
      const char *port_number =
        ACE_OS::getenv ("TradingServicePort");

      if (port_number != 0)
        port = static_cast<u_short> (ACE_OS::atoi (port_number));
      else
        port = TAO_DEFAULT_TRADING_SERVER_REQUEST_PORT;
    }

  // Instantiate a server that will receive requests for an ior
  if (mde.length () != 0)
    {
      if (this->ior_multicast_.init ((char *) this->ior_.in (),
                                     mde.c_str (),
                                     TAO_SERVICEID_TRADINGSERVICE) == -1)
        return -1;
    }
  else
    {
      if (this->ior_multicast_.init ((char *) this->ior_.in (),
                                     port,
                                     ACE_DEFAULT_MULTICAST_ADDR,
                                     TAO_SERVICEID_TRADINGSERVICE) == -1)
        ORBSVCS_ERROR_RETURN ((LM_ERROR,
                           "Failed to init IOR multicast.\n"),
                          -1);
    }

  // Register event handler for the ior multicast.
  if (reactor->register_handler (&this->ior_multicast_,
                                 ACE_Event_Handler::READ_MASK) == -1)
    ORBSVCS_DEBUG ((LM_DEBUG,
                "cannot register Event handler\n"));
  else
    ORBSVCS_DEBUG ((LM_DEBUG,
                "The multicast server setup is done.\n"));

  // Other trader instances will bootstrap to us.
  this->bootstrapper_ = 1;

#endif /* ACE_HAS_IP_MULTICAST */
  return 0;
}
Example #26
0
// Install ior multicast handler.
int
TAO_IFR_Server::init_multicast_server (void)
{
#if defined (ACE_HAS_IP_MULTICAST)
  // Get reactor instance from TAO.
  ACE_Reactor *reactor = this->orb_->orb_core ()->reactor ();

  // See if the -ORBMulticastDiscoveryEndpoint option was specified.
  ACE_CString mde (
      TAO_ORB_Core_instance ()->orb_params ()->mcast_discovery_endpoint ()
    );

  // First, see if the user has given us a multicast port number
  // on the command-line;
  u_short port =
    TAO_ORB_Core_instance ()->orb_params ()->service_port (
                                                 TAO::MCAST_INTERFACEREPOSERVICE
                                               );

  if (port == 0)
    {
      // Check environment var. for multicast port.
      const char *port_number =
        ACE_OS::getenv ("InterfaceRepoServicePort");

      if (port_number != 0)
        port = static_cast<u_short> (ACE_OS::atoi (port_number));
    }

  // Port wasn't specified on the command-line or in environment -
  // use the default.
  if (port == 0)
    port = TAO_DEFAULT_INTERFACEREPO_SERVER_REQUEST_PORT;

  // Instantiate a handler which will handle client requests for
  // the IFR ior, received on the multicast port.
  ACE_NEW_THROW_EX (this->ior_multicast_,
                    TAO_IOR_Multicast (),
                    CORBA::NO_MEMORY ());

  if (mde.length () != 0)
    {
      if (this->ior_multicast_->init (this->ifr_ior_.in (),
                                      mde.c_str (),
                                      TAO_SERVICEID_INTERFACEREPOSERVICE)
           == -1)
        {
          ORBSVCS_ERROR_RETURN ((
              LM_ERROR,
              ACE_TEXT ("Interface Repository: cannot initialize ")
              ACE_TEXT ("multicast event handler\n")
            ),
            -1
          );
        }
    }
  else
    {
      if (this->ior_multicast_->init (this->ifr_ior_.in (),
                                      port,
                                      ACE_DEFAULT_MULTICAST_ADDR,
                                      TAO_SERVICEID_INTERFACEREPOSERVICE)
           == -1)
        {
          ORBSVCS_ERROR_RETURN ((
              LM_ERROR,
              ACE_TEXT ("Interface Repository: cannot initialize ")
              ACE_TEXT ("multicast event handler\n")
            ),
            -1
          );
        }
    }

  // Register event handler for the ior multicast.
  if (reactor->register_handler (this->ior_multicast_,
                                 ACE_Event_Handler::READ_MASK)
       == -1)
    {
      ORBSVCS_ERROR_RETURN ((
          LM_ERROR,
          ACE_TEXT ("Interface Repository: cannot register ")
          ACE_TEXT ("multicast event handler\n")
        ),
        -1
      );
    }

#endif /* ACE_HAS_IP_MULTICAST */

  return 0;
}
Example #27
0
//---------------------------------------------------------------------------
int ACE_MAIN(int argc, ACE_TCHAR  *argv[])
{
	// 환경설정 (제일 먼저 초기화 해야함)
	procArguments(argc, argv);

	// 로그
	if(initLog() < 0)
	{
		printf("로그 초기화를 실패했으므로 프로그램을 종료합니다.\n");
		return -1;
	}

	//-----------------------------------------------------------------------
	// 데몬 만들기 
	//-----------------------------------------------------------------------
	// acceptor 가 초기화 된 후 데몬을 만들게 되면, 부모프로세스가 제거되면서
	// listen 소켓도 같이 제거된다. 그러므로 acceptor 를 초기화 하기 전에
	// 데몬을 먼저 만들어야 한다.
	if(Config::instance()->process.daemon == true)
	{
		if(makeDaemon() < 0)
		{
			printf("데몬으로 만들기를 실패했으므로 프로그램을 종료합니다.\n");
			return -1;
		}
	}
	
	PAS_NOTICE1("%s", compile_date);

	// 시그널 핸들러
	PasSignalHandler* pSignalHandler = new PasSignalHandler;
	initSignal(pSignalHandler);

	//------------------
	// 각 모듈의 초기화
	//------------------
	HTTP::Request::HeaderBuffBytes = HTTP::Response::HeaderBuffBytes = Config::instance()->process.HttpHeaderBufferBytes;
	
	increseFdLimit();

	
	// PAS 공식 로그
	char hostName[32];

	gethostname(hostName, sizeof(hostName)-1);
	PasDataLog::setPasAddr(hostName);
	
	// 메모리 매니저 초기화
	//initMessageBlockManager();
	if (readMBconfig() < 0)
	{
		printf("메모리 풀 컨피그 설정값을 확인하세요.\n");
		PAS_ERROR("메모리 풀 컨피그 설정값을 확인하세요.\n");
		return -1;
	}

	const int numWorkerThread = Config::instance()->thread.numWorker;

	// 리액터
	ACE_Reactor* pReactor = ReactorPool::instance()->createMaster();
	
	ReactorPool::instance()->createWorkers(numWorkerThread);

	ACE_Reactor* pGlobalReactor = ACE_Reactor::instance();

	PAS_NOTICE3("REACTOR: Master=%X, Global=%X, Master=%x", 
		pReactor,  pGlobalReactor, ReactorPool::instance()->masterReactor());

	// Listen 포트 설정
	PAS_NOTICE("Listen Socket Activate");
	PasAcceptor* pAcceptor = new PasAcceptor(pReactor);
	
	const int listenPort = Config::instance()->network.listenPort;

	// mIDC 내의 서버를 감시하는 쪽에 mwatch 전달하기 위해 메시지 작성한다.
	Util2::setMwatchMsg(listenPort);

	// acceptor 기동 
	if(pAcceptor->open(listenPort) < 0)
	{
		PAS_ERROR1("Listen 소켓 생성 실패, Port[%d]\n", listenPort);
		PAS_ERROR("프로그램 종료\n");

		printf("Listen 소켓 생성 실패, Port[%d]\n", listenPort);
		printf("프로그램 종료\n");
		return -1;
	}

	// 쓰레드 매니저
	ACE_Thread_Manager* pTManager = ACE_Thread_Manager::instance();	

	// monitor 보고리를 위한 thread 를 생성한다.
	MonitorReporter *monitor = MonitorReporter::instance(pTManager);
	monitor->activate(THR_NEW_LWP | THR_JOINABLE);

	WatchReporter *watch = WatchReporter::instance(pTManager);
	watch->activate(THR_NEW_LWP | THR_JOINABLE);

	// UserInfo 관리를 위한 thread 를 생성한다.
	UserInfoMng *userInfoMng = UserInfoMng::instance(pTManager);
	userInfoMng->activate(THR_NEW_LWP | THR_JOINABLE);
	
	// phone trace 를 위한 thread 를 생성한다.
	PhoneTraceMng *phoneTraceMng = PhoneTraceMng::instance(pTManager);
	phoneTraceMng->setDataFile((char*)"trace.acl");
	phoneTraceMng->activate(THR_NEW_LWP | THR_JOINABLE);

	// 공지 처리 (Stat Filter)  를 위한 thread 를 생성한다.
	StatFilterMng *statFilterMng = StatFilterMng::instance(pTManager);
	statFilterMng->setDataFile((char*)"k_stat.cfg");
	statFilterMng->activate(THR_NEW_LWP | THR_JOINABLE);

	// ACL 초기화
	if(Config::instance()->acl.enable)
		initACL();

	CGI::cgiSetupConstants();
	
	// Create AuthAgent Thread
	AuthAgent *authAgent = AuthAgent::instance(pTManager);
	authAgent->activate(THR_NEW_LWP | THR_JOINABLE);

	//usleep(1000);
	
	// 내부 정보 (sysinfo) 출력를 위한 Thread
	SysInfo  *sysInfo = SysInfo::instance(pTManager);
	sysInfo->activate(THR_NEW_LWP | THR_JOINABLE);

	// hash key 로그 작성을 위한 초기화.
	HashKey::prepare();
	
	// 로그 화일을 먼저 만들어 놓는다.  테스트시에 편하다. (tail -f )
	PasDataLog::instance();
	
	// accept event 핸들러 등록
	pReactor->register_handler(pAcceptor, ACE_Event_Handler::ACCEPT_MASK);

	// 이벤트 디멀티플렉싱
	PAS_NOTICE("Master Reactor Start");
	pReactor->run_event_loop();
	PAS_NOTICE("Master Reactor Stop");

	ReactorPool::instance()->stopWorkers();


	/*--- Reactor 가 종료된 경우 아래 라인으로 진행된다. ---*/

	stopACL(); // ACL 종료
	userInfoMng->stop();
	monitor->stop();
	watch->stop();
	phoneTraceMng->putq(new ACE_Message_Block());
	statFilterMng->putq(new ACE_Message_Block());
	sysInfo->putq(new ACE_Message_Block());
	authAgent->putq(new ACE_Message_Block());

	DNS::Manager::instance()->removeAllQuerier();
	
	// 모든 쓰레드 종료 대기
	PAS_NOTICE("Waiting for all threads to stop");
	pTManager->wait();

	delete phoneTraceMng;
	delete statFilterMng;
	delete sysInfo;
	// 생성한 동적 객체 삭제
	delete pSignalHandler;
	
	PAS_NOTICE("======= PAS GW Stop =======");

	return 0;
}