Merge branch 'master' into jwi-bcc64xsingletonwarning
[ACE_TAO.git] / ACE / examples / C++NPv1 / Thread_Per_Connection_Logging_Server.cpp
blob6fc5d3950493533b04fa23361388cfc257dd133c
1 /*
2 ** Copyright 2001 Addison Wesley. All Rights Reserved.
3 */
5 #include "ace/FILE_IO.h"
6 #include "ace/Log_Msg.h"
7 #include "ace/Signal.h"
8 #include "ace/Thread_Manager.h"
10 #include "Thread_Per_Connection_Logging_Server.h"
11 #include "Logging_Handler.h"
13 #include <errno.h>
14 #include <memory>
16 namespace {
17 extern "C" void sigterm_handler (int /* signum */) { /* No-op. */ }
21 ACE_THR_FUNC_RETURN Thread_Per_Connection_Logging_Server::run_svc (void *arg)
23 std::unique_ptr<Thread_Args> thread_args (static_cast<Thread_Args *> (arg));
25 thread_args->this_->handle_data (&thread_args->logging_peer_);
26 thread_args->logging_peer_.close ();
27 return 0; // Return value is ignored
31 int
32 Thread_Per_Connection_Logging_Server::handle_connections ()
34 std::unique_ptr<Thread_Args> thread_args (new Thread_Args (this));
36 if (acceptor ().accept (thread_args->logging_peer_) == -1)
37 return -1;
38 if (ACE_Thread_Manager::instance ()->spawn (
39 // Pointer to function entry point.
40 Thread_Per_Connection_Logging_Server::run_svc,
41 // <run_svc> parameter.
42 static_cast<void *> (thread_args.get ()),
43 THR_DETACHED | THR_SCOPE_SYSTEM) == -1)
44 return -1;
45 thread_args.release (); // Spawned thread now owns memory
46 return 0;
50 int
51 Thread_Per_Connection_Logging_Server::handle_data (ACE_SOCK_Stream *client)
53 ACE_FILE_IO log_file;
54 // Client's hostname is logfile name.
55 make_log_file (log_file, client);
57 // Place the connection into blocking mode since this
58 // thread isn't doing anything except handling this client.
59 client->disable (ACE_NONBLOCK);
61 Logging_Handler logging_handler (log_file, *client);
63 // Keep handling log records until client closes connection
64 // or this thread is asked to cancel itself.
65 ACE_Thread_Manager *mgr = ACE_Thread_Manager::instance ();
66 ACE_thread_t me = ACE_Thread::self ();
67 while (!mgr->testcancel (me) &&
68 logging_handler.log_record () != -1)
69 continue;
71 log_file.close ();
72 return 0;
76 int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
78 // Register to receive the <SIGTERM> signal.
79 ACE_Sig_Action sa ((ACE_SignalHandler) sigterm_handler,
80 SIGTERM);
82 Thread_Per_Connection_Logging_Server server;
84 if (server.run (argc, argv) == -1)
85 ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "server.run()"), 1);
87 // Cooperative thread cancellation and barrier synchronization.
88 ACE_Thread_Manager::instance ()->cancel_all ();
89 return ACE_Thread_Manager::instance ()->wait ();