    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Orderly Termination of Programs</title>
        <link>https://members.accu.org/index.php/articles/1536</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #89 - February 2009</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c249/">89</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-249/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+249/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Orderly Termination of Programs</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 16 February 2009 08:57:00 +00:00 or Mon, 16 February 2009 08:57:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Ensuring a clean shutdown is important. Omar Bashir presents some techniques.</p>
<p><strong>Body:</strong>&nbsp;<p>Servers are processes, typically on networked computers, that encapsulate and manage a collection of related resources and present functionality related to these resources to client applications
				      [<a href="#Coulouris01">Coulouris01</a>]
				. Servers wait continuously for requests from clients. Upon receiving requests, servers service the requests and then wait for further requests. As many other applications depend upon servers, termination of their execution should be achieved in an orderly manner. This allows the dependencies to be brought to a state to allow an error-free restart. Also the clients in the process of being served need to either be notified or allowed to complete their sessions.
  </p><p>
    Servers can be terminated in one of the following two ways,
  </p>
		<ol><li>
    Sending a special application level termination request.
  </li><li>
    Sending an operating system level signal to the server.
  </li></ol><p>
    The former is implemented completely at the application level and can be relatively conveniently synchronized with the operation of the server to perform an orderly shutdown. This method is only useful for networked applications.
  </p><p>
    However, the latter originates from the operating system (albeit triggered by another application) and needs to be handled by a callback mechanism in the destination server. Furthermore, this approach can also be used to implement orderly termination in standalone applications, as this does not require communicating program termination commands via a networked connection.
  </p><p>
    Most programming languages provide language level constructs to receive signals (including termination signals) from operating systems. Applications can register callbacks to be triggered on the occurrence of these signals. For signals indicating application termination, registered callbacks can initiate an orderly termination of the application. Most such callbacks may follow a pattern. An object-oriented generalization of one of such patterns is discussed in this article. A simple framework that implements this pattern in C++ is described. This implementation is specific to the Linux platform. Application of this framework in single threaded and multithreaded programs is also illustrated.
  </p><h2>
    An orderly termination mechanism
  </h2><p>
    Servers operate in a loop, i.e., wait for requests to arrive. Once the requests arrive, they process these requests and then wait for further requests. The simplest way to manage orderly termination of a server is to set a flag (referred here to as the shutdown flag) when the server is to be terminated. The server should continuously monitor the shutdown flag and if it is set, the server should initiate the termination process.
  </p><p>
    Stevens differentiates servers as iterative and concurrent
				      [<a href="#Stevens99">Stevens99</a>]
				. Iterative servers handle only one request at a time. If another request arrives while the server is processing a previous request, the new request is queued and is processed once the previous request has been processed. Managing orderly termination in iterative servers can be relatively straightforward and a possible means of achieving this is shown in the state diagram in figure 1.
<table class="sidebartable"><tr><td><img src="/content/images/journals/ol89/Overload%20WW%20XML%20and%20CSS-4-1-2.gif"/></td></tr><tr><td class="title">Figure 1</td></tr></table></p><p>
    The server, after initialization, waits for client's requests. In case the request is received, the server processes the request. After processing the request it checks the shutdown flag to determine if a shutdown was initiated. If that flag is set, the server performs the termination operations, e.g., closing down files, database connections etc. If the flag is not set then the server waits for the next request. In case no request arrives, the server times out and checks the shutdown flag in case program termination was initiated while the server was waiting for the request. If that flag is not set then the server again waits for a client's request. Alternatively, if this flag is set, the server performs the necessary termination operations.
  </p><p>
    Concurrent servers handle multiple requests at one time. There are several approaches to this. A traditional mechanism is to call the Unix fork function to create a separate child process for each client or request. Alternatively threads are spawned instead of child processes to service each client or client's request. Orderly termination of concurrent servers may require a slightly more elaborate process but follows a pattern similar to that for iterative servers.
  </p><p>
    The state transition diagram in figure 2 shows orderly termination of concurrent servers. Upon receiving a request, the server will spawn a thread to service the request. If the shutdown flag has been set, the server will wait for all the threads it spawned earlier to terminate before initiating server termination.
<table class="sidebartable"><tr><td><img src="/content/images/journals/ol89/Overload%20WW%20XML%20and%20CSS-4-1-3.gif"/></td></tr><tr><td class="title">Figure 2</td></tr></table></p><p>
    Finally, a multithreaded server can have a number of continuously running threads, which may service incoming requests independently (therefore, operating as a concurrent server) or they may assist in servicing a single request (therefore, operating as a multithreaded iterative server). Figure 3 shows orderly termination of a multithreaded server with continuously running threads.
<table class="sidebartable"><tr><td><img src="/content/images/journals/ol89/Overload%20WW%20XML%20and%20CSS-4-1-4.gif"/></td></tr><tr><td class="title">Figure 3</td></tr></table></p><p>
    Once the server receives a signal to terminate operation, it signals all the threads to terminate their operations. Individual threads within the server may be viewed as iterative servers for this purpose. After signaling all the threads to terminate, the server waits for the threads to join. Once all the threads have joined, the server terminates its operation.
  </p><h2>
    Class structures and dynamics
  </h2><p>
    In the simplest case, a termination handler is based on two participants. As shown in the class diagram in figure 4, these are the <tt class="code">ShutdownManager</tt> class and the list of <tt class="code">Subject</tt>s that are notified of imminent program termination by the <tt class="code">ShutdownManager</tt>. A <tt class="code">Subject</tt> can be the complete application wrapper or individual classes within the application, e.g., database handler, socket wrapper, etc. A <tt class="code">Subject</tt> should at least implement the <tt class="code">Haltable</tt> interface, which should present a method (<tt class="code">shutdown()</tt>) to be called by the <tt class="code">ShutdownManager</tt> object to notify imminent program termination and a method (<tt class="code">isShuttingDown()</tt>) to determine if the <tt class="code">Subject</tt> is shutting down in response to a call to the <tt class="code">shutdown()</tt> method.
<table class="sidebartable"><tr><td><img src="/content/images/journals/ol89/Overload%20WW%20XML%20and%20CSS-4-1-5.gif"/></td></tr><tr><td class="title">Figure 4</td></tr></table></p><p>
    Programs using this pattern will have to declare an object of the <tt class="code">ShutdownManager</tt> class and register all instances of implementations of <tt class="code">Haltable</tt> using the <tt class="code">addHaltable()</tt> method. Programs will have to register a callback to receive the program termination signal from the operating system. This callback will call the <tt class="code">executeShutdown()</tt> method of the <tt class="code">ShutdownManager</tt> instance, which will iterate through the list of registered <tt class="code">Haltable</tt> instances and call their <tt class="code">shutdown()</tt> methods.
<table class="sidebartable"><tr><td><img src="/content/images/journals/ol89/Overload%20WW%20XML%20and%20CSS-4-1-6.gif"/></td></tr><tr><td class="title">Figure 5</td></tr></table></p><p>
    Implementation of <tt class="code">Termination Handler</tt> as shown in figure 4 may be sufficient for single threaded programs. However, for multithreaded programs, <tt class="code">Termination Handler</tt> needs to be extended as shown in figure 5. Here, the <tt class="code">Subject</tt> needs to implement the <tt class="code">Runnable</tt> interface, which extends the <tt class="code">Haltable</tt> interface. <tt class="code">Subject</tt>s that need to be executed in separate threads are not directly registered with the <tt class="code">ShutdownManager</tt>. Rather they need to be decorated by objects of the <tt class="code">ThreadOwner</tt> class (Decorator pattern,
				      [<a href="#Gamma95">Gamma95</a>]
				. <tt class="code">ThreadOwner</tt> also implements the<tt class="code"> Haltable</tt> interface, therefore allowing objects of the <tt class="code">ThreadOwner</tt> class to be registered with the <tt class="code">ShutdownManager</tt>. Objects of the <tt class="code">ThreadOwner</tt> class execute implementations of <tt class="code">Runnable</tt> in separate threads. Furthermore, they can allow orderly shutdown in a thread-safe manner. When called from  <tt class="code">executeShutdown()</tt>, the <tt class="code">shutdown()</tt> method of the <tt class="code">ThreadOwner</tt> class locks a mutex and then calls the <tt class="code">shutdown()</tt> method of the <tt class="code">Subject</tt> allowing the thread in which the <tt class="code">Subject</tt> is executing to terminate appropriately. Similarly, the <tt class="code">isShuttingDown()</tt> method of the <tt class="code">ThreadOwner</tt> class locks the mutex and then calls the <tt class="code">isShuttingDown()</tt> method of the <tt class="code">Subject</tt>. As <tt class="code">isShuttingDown()</tt> method is also called by the <tt class="code">Haltable</tt> implementations internally to determine when to terminate their operations, <tt class="code">Runnable</tt> implementations require a reference to their respective <tt class="code">ThreadOwner</tt> instances so that they can access and invoke the decorated (and thread safe) <tt class="code">isShuttingDown()</tt> method provided by the <tt class="code">ThreadOwner</tt>. The <tt class="code">setThreadOwner()</tt> method of a <tt class="code">Runnable</tt> implementation is used to establish this association.
<table class="sidebartable"><tr><td><img src="/content/images/journals/ol89/Overload%20WW%20XML%20and%20CSS-4-1-7.gif"/></td></tr><tr><td class="title">Figure 6</td></tr></table></p><p>
    Once the <tt class="code">executeShutdown()</tt> method of the <tt class="code">ShutdownManager</tt> instance is called, it first iterates through the list of registered <tt class="code">Haltable</tt> instances and calls their respective <tt class="code">shutdown()</tt> methods. Then it again iterates through this list and for every <tt class="code">Haltable</tt>, which is also a <tt class="code">ThreadOwner</tt>, it calls the <tt class="code">join()</tt> method of the <tt class="code">ThreadOwner</tt> to wait for the respective thread to join (Figure 6). Therefore, when <tt class="code">executeShutdown()</tt> returns, all registered <tt class="code">Haltable</tt> instances have been notified of termination and if they have been executing in separate threads, those threads should have joined thus allowing the server to terminate in an orderly manner.
  </p><h2>
    Implementation in C++
  </h2><p>
    Listing 1 shows the C++ implementation of the <tt class="code">Haltable</tt> interface.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef HALTABLE_H_
    #define HALTABLE_H_
    namespace haltable{
      class Haltable
      {
        public:
          virtual void shutdown(void)  = 0;
          virtual bool isShuttingDown(void) = 0;
          virtual ~Haltable(){}
      };
    }
    #endif /*HALTABLE_H_*/
</pre></td></tr><tr><td class="title">Listing 1</td></tr></table><p>
    As mentioned earlier, each <tt class="code">Haltable</tt> implementation has to implement the <tt class="code">shutdown()</tt> method that specifies the operations to be performed for that <tt class="code">Haltable</tt> implementation upon shutdown. Also <tt class="code">isShuttingDown()</tt> needs to be implemented to allow the calling method to determine if <tt class="code">shutdown()</tt> had already been called and the <tt class="code">Haltable</tt> implementation is in the process of terminating its operation. <tt class="code">isShuttingDown()</tt> will typically be called inside the main functional loop of the <tt class="code">Haltable</tt> implementation so that the loop can be exited in response to a shutdown notification.
  </p><p>
    Listing 2 shows the <tt class="code">Runnable</tt> interface. This C++ implementation of the <tt class="code">Runnable</tt> interface is actually an abstract class. It holds a pointer to the <tt class="code">ThreadOwner</tt> object that will execute a concrete subclass of <tt class="code">Runnable</tt> in a separate thread. As mentioned earlier, this association with the <tt class="code">ThreadOwner</tt> object is required to allow execution of thread safe implementations of <tt class="code">shutdown()</tt> and <tt class="code">isShuttingdown()</tt> methods provided by <tt class="code">ThreadOwner</tt> when invoked from within the <tt class="code">Runnable</tt> implementations. This association is established by calling the <tt class="code">setThreadOwner()</tt> method and passing it the pointer to the <tt class="code">ThreadOwner</tt> object which executes this <tt class="code">Runnable</tt> implementation in a separate thread. Finally, the functionality of a <tt class="code">Runnable</tt> implementation to be executed in its separate thread is implemented in the <tt class="code">execute()</tt> method.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef RUNNABLE_H_
    #define RUNNABLE_H_
    #include &quot;Haltable.h&quot;
    #include &lt;cstdio&gt;
    namespace haltable{
      class ThreadOwner;
      class Runnable: public virtual Haltable{
         protected:
           ThreadOwner* threadOwner;
         public:
          Runnable(void):threadOwner(NULL){}
          virtual void execute(void) = 0;
          virtual void setThreadOwner(
             ThreadOwner* threadHandler){
            threadOwner = threadHandler;
          }
          virtual ~Runnable(){}
       };
    };
    #endif /*RUNNABLE_H_*/
</pre></td></tr><tr><td class="title">Listing 2</td></tr></table><p>
    Listing 3 shows the <tt class="code">ThreadOwner</tt> class which is an implementation of the <tt class="code">Haltable</tt> interface.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef THREADOWNER_
    #define THREADOWNER_
    #include &quot;Runnable.h&quot;
    #include &lt;pthread.h&gt;
    #include &lt;stdexcept&gt;
    namespace haltable{
    void* executeInThread(void* runnableObj);
    enum ThreadStatus {
      THREAD_NOT_CREATED,
      THREAD_CREATED,
      ERROR_CREATING_THREAD
    };
    class ThreadOwner:public Haltable{
      private:
        std::string name;
        pthread_t threadId;
        Runnable* runnable;
        pthread_mutex_t shutdownMutex;
        ThreadStatus currentStatus;
      public:
        ThreadOwner(const std::string&amp; threadName,
           Runnable* runnableObj):name(threadName),
           runnable(runnableObj),
           currentStatus(THREAD_NOT_CREATED){
          pthread_mutex_init(&amp;shutdownMutex, NULL);
          runnable-&gt;setThreadOwner(this);
        }
        const std::string&amp; getName(void){
        return name;
        }
        ThreadStatus start(void){
          if (currentStatus == THREAD_NOT_CREATED){
            if (pthread_create(&amp;threadId, NULL,
               executeInThread, runnable) == 0){
              currentStatus = THREAD_CREATED;
            } else {
              currentStatus = ERROR_CREATING_THREAD;
            }
          }
          return currentStatus;
        }
        void join(void){
          if (currentStatus != THREAD_CREATED){
            std::domain_error exp(
               &quot;Thread has or could not be created.&quot;);
            throw exp;
          } else {
            pthread_join(threadId, NULL);
          }
        }
        virtual void shutdown(void) {
          pthread_mutex_lock(&amp;shutdownMutex);
          runnable-&gt;shutdown();
          pthread_mutex_unlock(&amp;shutdownMutex);
        }
        virtual bool isShuttingDown(void) {
          bool reply = false;
          pthread_mutex_lock(&amp;shutdownMutex);
          reply = runnable-&gt;isShuttingDown();
          pthread_mutex_unlock(&amp;shutdownMutex);
          return reply;
        }
        virtual ~ThreadOwner(){
          pthread_mutex_destroy(&amp;shutdownMutex);
        }
      };
    };
    #endif /*THREADOWNER_*/
</pre></td></tr><tr><td class="title">Listing 3</td></tr></table><p>
    A <tt class="code">ThreadOwner</tt> instance is used to invoke the <tt class="code">execute()</tt> method of an instance of a <tt class="code">Runnable</tt> implementation in a separate thread. Thus, for multithreaded applications, <tt class="code">ThreadOwner</tt> is used as a <tt class="code">Subject</tt> for the <tt class="code">ShutdownManager</tt> instance. <tt class="code">ThreadOwner</tt> uses a mutex, which is locked when the <tt class="code">shutdown()</tt> and <tt class="code">isShuttingDown()</tt> methods of the <tt class="code">Runnable</tt> instance are called from the <tt class="code">shutdown()</tt> and <tt class="code">isShuttingDown()</tt> implementations of <tt class="code">ThreadOwner</tt> thus avoiding any race condition. Constructor of <tt class="code">ThreadOwner</tt> also calls the <tt class="code">setThreadOwner()</tt> of the <tt class="code">Runnable</tt> instance passed to the constructor as a parameter and passes its own pointer to the <tt class="code">Runnable</tt> instance. This allows the instance of <tt class="code">Runnable</tt> implementation to call the decorated <tt class="code">shutdown()</tt> and <tt class="code">isShuttingDown()</tt> methods provided by the <tt class="code">ThreadOwner</tt> rather than using its own undecorated methods. <tt class="code">start()</tt> method of <tt class="code">ThreadOwner</tt> invokes the <tt class="code">executeInThread()</tt> function in a new thread. The argument of this function is type-casted as a pointer to <tt class="code">Runnable</tt> and then its <tt class="code">execute()</tt> method is invoked to execute the functionality that the <tt class="code">Runnable</tt> instance provides. Listing 4 shows the implmentation of <tt class="code">executeInThread()</tt> function.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #include &quot;ThreadOwner.h&quot;

    void* haltable::executeInThread(void* runnableObj){
      Runnable* runnable = (Runnable*) runnableObj;
      runnable-&gt;execute();
      pthread_exit(NULL);
      return NULL;
    }
</pre></td></tr><tr><td class="title">Listing 4</td></tr></table><p>
    Listing 5 shows the <tt class="code">ShutdownManager</tt> implementation. <tt class="code">ShutdownManager</tt> implements a Singleton pattern
				      [<a href="#Gamma95">Gamma95</a>]
				 as only one instance of this class should be responsible for managing <tt class="code">Haltables</tt> and <tt class="code">ThreadOwners</tt> within a program. Therefore, the constructor is private. Pointer to an instance of this class is obtained by calling a static <tt class="code">initialise()</tt> method. This method increments the <tt class="code">refCount</tt> static variable of the class and creates an instance of this class if one has not already been created. Pointer to this instance is assigned to the instance static variable. The pointer to the instance of the class is then returned. Once the instance is no longer required, <tt class="code">dispose()</tt> method of the object is called. This method decrements the <tt class="code">refCount</tt> variable and once the value of the <tt class="code">refCount</tt> variable is zero, the instance of this class being pointed to by the instance class variable is deleted. As both <tt class="code">initialise()</tt> and <tt class="code">dispose()</tt> methods access static class members, they lock a mutex (<tt class="code">initMutex</tt>) to ensure thread safety. Finally, the <tt class="code">terminate()</tt> static method is used to destroy <tt class="code">initMutex</tt> which is statically initialized. The call to this method should be the last statement in a program.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef SHUTDOWNMANAGER_H_
    #define SHUTDOWNMANAGER_H_
    #define SHUTDOWN_MANAGER_DEBUG

    #include &lt;list&gt;
    #include &quot;Haltable.h&quot;
    #include &quot;ThreadOwner.h&quot;
    #include &lt;csignal&gt;
    #include &lt;pthread.h&gt;
    #include &lt;unistd.h&gt;
    #include &lt;stdexcept&gt;
    #include &lt;iostream&gt;

    namespace haltable{
    void handler(int sig);

    class ShutdownManager{
      private:
        std::list&lt;Haltable*&gt; haltables;
        int pipeDescriptors[2];
        static ShutdownManager* instance;
        static int refCount;
        static pthread_mutex_t initMutex;
        ShutdownManager(void): haltables(){
          struct sigaction termAction;
          sigemptyset(&amp;termAction.sa_mask);
          termAction.sa_handler = handler;
          termAction.sa_flags = 0;
          pipe(pipeDescriptors);
          sigaction(SIGTERM, &amp;termAction, NULL);
        }

      public:
        static ShutdownManager* initialise(void){
          pthread_mutex_lock(&amp;initMutex);
          refCount++;
          if (NULL == instance){
            instance = new ShutdownManager();
          }
          pthread_mutex_unlock(&amp;initMutex);
          return instance;
        }
        void dispose(void){
          pthread_mutex_lock(&amp;initMutex);
          refCount--;
          if ((NULL != instance) &amp;&amp; (refCount == 0)){
            delete instance;
            instance = NULL;
          }
          pthread_mutex_unlock(&amp;initMutex);
        }
        static void terminate(void){
          pthread_mutex_destroy(&amp;initMutex);
        }
        void addHaltable(Haltable* haltable){
          haltables.push_back(haltable);
        }
        void executeShutdown(void){
          for (std::list&lt;Haltable*&gt;::iterator itr =
             haltables.begin();
            itr != haltables.end(); itr++){
              (*itr)-&gt;shutdown();
          }
          for (std::list&lt;Haltable*&gt;::iterator itr =
             haltables.begin();
            itr != haltables.end(); itr++){
              ThreadOwner* threadOwner =
                 dynamic_cast&lt;ThreadOwner*&gt;(*itr);
             if (threadOwner != NULL){
              try{
                threadOwner-&gt;join();
              } catch(const std::domain_error&amp; exp){
                std::cout &lt;&lt; exp.what() &lt;&lt; std::endl;
              }
             }
          }
          char continueChar = 'x';
          write(pipeDescriptors[1], &amp;continueChar,
             sizeof(continueChar));
        }
       void waitForExecuteShutdown(void){
          char continueChar;
          while (read(pipeDescriptors[0],
             &amp;continueChar,
             sizeof(continueChar)) != 1){}
          close(pipeDescriptors[0]);
          close(pipeDescriptors[1]);
        }
    };
    };

    #endif /*SHUTDOWNMANAGER_H_*/
</pre></td></tr><tr><td class="title">Listing 5</td></tr></table><p>
    The constructor of this class specifies the <tt class="code">handler()</tt> function as the signal handler for the <tt class="code">SIGTERM</tt> signal, the signal sent to a process to notify its termination. The constructor also creates a pipe
				      [<a href="#Stevens99b">Stevens99b</a>]
				 to communicate that all the <tt class="code">Haltable</tt>s have been notified of shutdown and all the <tt class="code">ThreadOwner</tt>s have joined. The <tt class="code">handler()</tt> function is invoked once the <tt class="code">SIGTERM</tt> signal is received by the process. <tt class="code">handler()</tt> blocks the <tt class="code">SIGTERM</tt> signal and then invokes the <tt class="code">executeShutdown()</tt> method of the <tt class="code">ShutdownManager</tt>'s instance. <tt class="code">executeShutdown()</tt> invokes the <tt class="code">shutdown()</tt> methods of all registered <tt class="code">Haltable</tt>s and then for all <tt class="code">Haltable</tt>s that are also <tt class="code">ThreadOwner</tt>s, it invokes their <tt class="code">join()</tt> methods to wait for them to terminate before proceeding. <tt class="code">executeShutdown()</tt> then writes a character to the pipe created in the <tt class="code">constructor</tt>. The <tt class="code">main()</tt> function of the program should, at the end, call the <tt class="code">waitForExecuteShutdown()</tt> method of the <tt class="code">ShutdownManager</tt>'s instance. <tt class="code">waitForExecuteShutdown()</tt> blocks to read a character from the pipe created in the constructor of <tt class="code">ShutdownManager</tt>. In a multithreaded application, this allows the <tt class="code">main()</tt> function to wait for the <tt class="code">executeShutdown()</tt> method to end before ending the <tt class="code">main()</tt> function ensuring that all threads have terminated normally.
  </p><p>
    Listing 6 shows the implementation of the <tt class="code">handler()</tt> function and also the initialisation of the static data members of <tt class="code">ShutdownManager</tt>.  <tt class="code">handler()</tt> obtains the pointer to the instance of <tt class="code">ShutdownManager</tt> by call its <tt class="code">initialise()</tt> static method. Once it has completed its operation, it releases the instance by calling the <tt class="code">dispose()</tt> method on the object.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #include &quot;ShutdownManager.h&quot;
    haltable::ShutdownManager* haltable::ShutdownManager::instance = NULL;
    int haltable::ShutdownManager::refCount = 0;
    pthread_mutex_t haltable::ShutdownManager::initMutex = PTHREAD_MUTEX_INITIALIZER;
    void haltable::handler(int sig){
      haltable::ShutdownManager* shutdownManager =
         haltable::ShutdownManager::initialise();
      struct sigaction termAction;
      sigemptyset(&amp;termAction.sa_mask);
      termAction.sa_handler = SIG_IGN;
      termAction.sa_flags = 0;
      sigaction(SIGTERM, &amp;termAction, NULL);
      shutdownManager-&gt;executeShutdown();
      shutdownManager-&gt;dispose();
    }
</pre></td></tr><tr><td class="title">Listing 6</td></tr></table><h2>
    Example - a single threaded application
  </h2><p>
    Listing 7 shows an implementation of a <tt class="code">Haltable</tt> called the <tt class="code">SingleThreadedTimeLogger</tt>. Its <tt class="code">execute()</tt> method opens a specified file and logs system time in that file after every second as long as the <tt class="code">isShuttingDown()</tt> method returns <tt class="code">false</tt>. Once the <tt class="code">isShuttingDown()</tt> method returns <tt class="code">true</tt>, the <tt class="code">execute()</tt> method exits the loop and closes the file before ending. The <tt class="code">shutdown()</tt> method simply sets the <tt class="code">shutdownFlag</tt> whereas the <tt class="code">isShuttingDown()</tt> method returns the value of that flag.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef SINGLETHREADEDTIMELOGGER_H_
    #define SINGLETHREADEDTIMELOGGER_H_
    #include &quot;Haltable.h&quot;
    #include &lt;fstream&gt;
    #include &lt;string&gt;
    #include &lt;ctime&gt;
    #include &lt;cstdlib&gt;
    #include &lt;unistd.h&gt;
    #include &lt;iostream&gt;

    class SingleThreadedTimeLogger:
       virtual public haltable::Haltable{
      private:
        std::ofstream outFile;
        bool shutdownFlag;
        int sleepTime;
        std::string message;
      protected:
        std::string outFileName;
        bool openFile(void){
          outFile.open(outFileName.c_str());
          return outFile.good();
        }
        void closeFile(void){
          outFile.close();
        }
        void writeTimeToFile(){
          char buffer[128];
          time_t currentTime = time(NULL);
          ctime_r(&amp;currentTime, buffer);
          outFile &lt;&lt; message &lt;&lt; &quot; :: &quot; &lt;&lt; buffer;
          sleep(sleepTime);
        }
      public:
        SingleThreadedTimeLogger(
           const std::string&amp; fileName,
           const std::string&amp; msg):outFile(),
           shutdownFlag(false),
           sleepTime(1),
           message(msg),
           outFileName(fileName){}
        virtual ~SingleThreadedTimeLogger(){
          if (outFile.is_open()){
            outFile.close();
          }
        }
        virtual void shutdown(void){
          shutdownFlag = true;
        }
        virtual bool isShuttingDown(void){
          return shutdownFlag;
        }
        void execute(void){
          if (openFile()){
            while (!isShuttingDown()){
              writeTimeToFile();
            }
            closeFile();
          } else {
            std::cout &lt;&lt; &quot;Error opening &quot;
               &lt;&lt; outFileName &lt;&lt; std::endl;
          }
        }
    };
    #endif /*SINGLETHREADEDTIMELOGGER_H_*/
</pre></td></tr><tr><td class="title">Listing 7</td></tr></table><p>
    Listing 8 shows the program that uses an object of <tt class="code">SingleThreadedTimeLogger</tt> class to log time into the specified file. The <tt class="code">main()</tt> function of the program instantiates <tt class="code">timeLogger</tt> object of the <tt class="code">SingleThreadedTimeLogger</tt> class. The <tt class="code">main()</tt> function also obtains the reference of <tt class="code">ShutdownManager</tt> class by calling its <tt class="code">initialise()</tt> static method and assigns it to <tt class="code">shutdownManager</tt> variable. <tt class="code">timeLogger</tt> is added to <tt class="code">shutdownManager</tt> object's list of <tt class="code">Haltable</tt>s by passing its pointer to the <tt class="code">addHaltable()</tt> method. After <tt class="code">timeLogger</tt> has been added to <tt class="code">shutdownHandler</tt>'s list of <tt class="code">Haltable</tt>s, its <tt class="code">execute()</tt> method is called to start the logging process.
  </p><p>
    To perform an orderly termination of this application, the user may determine the process ID using Linux's <tt class="code">ps</tt> command and then kill the application using the <tt class="code">kill &lt;process ID&gt;</tt> command. As a result, a <tt class="code">SIGTERM</tt> signal is sent to this application. Upon receipt, the <tt class="code">handler()</tt> function in ShutdownManager.h is executed to initiate an orderly termination of the program <a href="http://pentaxqreview.com/">Pentax Q Review</a>.
  </p><p>
    The <tt class="code">main()</tt> function releases the instance of the <tt class="code">ShutdownManager</tt> class  by calling the dispose method on the object pointed to by <tt class="code">shutdownManager</tt> pointer. Finally, before returning, the <tt class="code">terminate()</tt> static method of the <tt class="code">ShutdownManager</tt> class is called (see Listing 8).
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef THREADOWNER_
    #include &quot;ShutdownManager.h&quot;
    #include &quot;SingleThreadedTimeLogger.h&quot;
    #include &lt;fstream&gt;
    #include &lt;string&gt;
    #include &lt;ctime&gt;
    #include &lt;unistd.h&gt;
    #include &lt;iostream&gt;

    int main(void){
      haltable::ShutdownManager* shutdownManager =
         haltable::ShutdownManager::initialise();
      SingleThreadedTimeLogger timeLogger(
         &quot;time_log.txt&quot;, &quot;SingleThreadedTimeLogger&quot;);
      shutdownManager-&gt;addHaltable(&amp;timeLogger);
      timeLogger.execute();
      std::cout &lt;&lt; &quot;Exiting application&quot; &lt;&lt; std::endl;
      shutdownManager-&gt;waitForExecuteShutdown();
      shutdownManager-&gt;dispose();
      haltable::ShutdownManager::terminate();
      return 0;
    }
</pre></td></tr><tr><td class="title">Listing 8</td></tr></table><h2>
    Example - a multi-threaded application
  </h2><p>
    Listing 9 shows the <tt class="code">ThreadableTimeLogger</tt>, an extension of the <tt class="code">SingleThreadedTimeLogger</tt> (Listing 7) and the <tt class="code">Runnable</tt> (Listing 2) classes. Instances of this class can be executed in separate threads using instances of the <tt class="code">ThreadOwner</tt> class. Implementation of the <tt class="code">execute()</tt> method is similar to that of the  <tt class="code">SingleThreadedTimeLogger</tt> except that it uses the associated  <tt class="code">ThreadOwner</tt> instance to determine, by calling the <tt class="code">ThreadOwner</tt>'s <tt class="code">isShuttingDown()</tt> method, if its <tt class="code">shutdown()</tt> method has been called. This is because the <tt class="code">ThreadOwner</tt> instance calls <tt class="code">ThreadableTimeLogger</tt>'s <tt class="code">shutdown()</tt> and <tt class="code">isShuttingDown()</tt> methods after locking a mutex to avoid race conditions. As described earlier, the association between a <tt class="code">ThreadableTimeLogger</tt> instance and a <tt class="code">ThreadOwner</tt> instance is achieved via the <tt class="code">Runnable</tt> abstract class's <tt class="code">setThreadOwner()</tt> method.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #ifndef THREADABLETIMELOGGER_H_
    #define THREADABLETIMELOGGER_H_

    #include &quot;Runnable.h&quot;
    #include &quot;SingleThreadedTimeLogger.h&quot;
    #include &lt;pthread.h&gt;
    #include &lt;iostream&gt;

    class ThreadableTimeLogger:
       public SingleThreadedTimeLogger,
       public haltable::Runnable{
      public:
        ThreadableTimeLogger(
           const std::string&amp; fileName,
           const std::string&amp; msg):
           SingleThreadedTimeLogger(fileName, msg),
           Runnable(){}
        virtual ~ThreadableTimeLogger(){}

        void execute(void){
          if (openFile()){
            while (!threadOwner-&gt;isShuttingDown()){
              writeTimeToFile();
            }
            closeFile();
          } else {
            std::cout &lt;&lt; &quot;Error opening &quot; &lt;&lt;
               outFileName &lt;&lt; std::endl;
          }
        }

        virtual void shutdown(void){
          std::cout &lt;&lt; &quot;Shutdown called in
             ThreadableTimeLogger&quot; &lt;&lt; std::endl;
          SingleThreadedTimeLogger::shutdown();
        }

        virtual bool isShuttingDown(void){
          std::cout &lt;&lt; &quot;isShuttingDown called in
             ThreadableTimeLogger&quot; &lt;&lt; std::endl;
          return SingleThreadedTimeLogger::
             isShuttingDown();
        }
    };

    #endif /*THREADABLETIMELOGGER_H_*/
</pre></td></tr><tr><td class="title">Listing 9</td></tr></table><p>
    Listing 10 shows the program that uses three instances of <tt class="code">ThreadableTimeLogger</tt> to log time in three different files concurrently. The <tt class="code">main()</tt> function of this example creates three objects of the <tt class="code">ThreadableTimeLogger</tt> class and three objects of the <tt class="code">ThreadOwner</tt> class. Each <tt class="code">ThreadableTimeLogger</tt> instance is associated with a <tt class="code">ThreadOwner</tt> instance. <tt class="code">ThreadOwner</tt> instances are then added to the list of <tt class="code">Haltable</tt>s in the instance of the <tt class="code">ShutdownManager</tt> class. <tt class="code">start() </tt>is then called on each of these objects to start the respective threads for each of <tt class="code">ThreadableTimeLogger</tt> instances to invoke their <tt class="code">execute()</tt> methods in. <tt class="code">main()</tt> then calls the <tt class="code">waitForExecuteShudown()</tt> method of the <tt class="code">ShutdownManager</tt>'s instance to block on the pipe internal to the <tt class="code">ShutdownManager</tt>'s instance waiting for the notification by the <tt class="code">executeShutdown()</tt> method to signal that all <tt class="code">Haltable</tt>s have been notified of termination and all <tt class="code">ThreadOwner</tt>s have joined. This application can also be signaled to terminate by using Linux's kill command. As in the previous example, <tt class="code">handle()</tt> will call <tt class="code">executeShutdown()</tt> method of the <tt class="code">ShutdownManager</tt>'s instance. However, as all the <tt class="code">Haltable</tt>s in this case are also <tt class="code">ThreadOwner</tt>s, <tt class="code">executeShutdown()</tt> will wait for all the respective threads to join before returning.
  </p>
<table class="sidebartable"><tr><td><pre class="programlisting">
    #include &lt;fstream&gt;
    #include &quot;ShutdownManager.h&quot;
    #include &quot;ThreadableTimeLogger.h&quot;
    #include &lt;ctime&gt;
    #include &lt;string&gt;

    int main(void){
      haltable::ShutdownManager* shutdownManager =
         haltable::ShutdownManager::initialise();
      ThreadableTimeLogger timeLogger0(
         &quot;time_log_0.txt&quot;, &quot;InsideThreadA&quot;);
      ThreadableTimeLogger timeLogger1(
         &quot;time_log_1.txt&quot;, &quot;InsideThreadB&quot;);
      ThreadableTimeLogger timeLogger2(
         &quot;time_log_2.txt&quot;, &quot;InsideThreadC&quot;);

      haltable::ThreadOwner threadA(
         &quot;ThreadA&quot;, &amp;timeLogger0);
      haltable::ThreadOwner threadB(
         &quot;ThreadB&quot;, &amp;timeLogger1);
      haltable::ThreadOwner threadC(
         &quot;ThreadC&quot;, &amp;timeLogger2);

      shutdownManager-&gt;addHaltable(&amp;threadA);
      shutdownManager-&gt;addHaltable(&amp;threadB);
      shutdownManager-&gt;addHaltable(&amp;threadC);

      if (threadA.start() !=
         haltable::THREAD_CREATED){
        std::cout &lt;&lt; &quot;Error starting thread A&quot; &lt;&lt;
           std::endl;
      }
      if (threadB.start() !=
         haltable::THREAD_CREATED){
        std::cout &lt;&lt; &quot;Error starting thread B&quot; &lt;&lt;
           std::endl;
      }
      if (threadC.start() !=
         haltable::THREAD_CREATED){
        std::cout &lt;&lt; &quot;Error starting thread C&quot; &lt;&lt;
           std::endl;
      }
        shutdownManager-&gt;waitForExecuteShutdown();
      std::cout &lt;&lt; &quot;Terminating application&quot; &lt;&lt;
         std::endl;
      shutdownManager-&gt;dispose();
      haltable::ShutdownManager::terminate();
      return (0);
    }
</pre></td></tr><tr><td class="title">Listing 10</td></tr></table><h2>
    Concluding remarks
  </h2><p>
    Ensuring orderly termination of applications, particularly servers, can end up being complicated. Various resources being used by these applications need to be brought to consistent states for subsequent error-free restart and various clients need to either be notified of the shutdown or their requests completed before the shutdown. Large applications may contain several objects of many different classes that typically are wrappers over system resources and need to be notified of an impending shutdown. This article has described a pattern that can be used in a framework to allow necessary operations to be performed by respective objects once the application has been notified of its termination. An implementation of a framework based on this pattern and two examples of its use are also described. This framework is written in C++ for Linux.</p><h2>
    Acknowledgements
  </h2><p>
    I am grateful to Ric Parkin and the reviewers for their valuable feedback and encouragement.
  </p><h2>
    References
  </h2><p class="bibliomixed"><a name="Coulouris01"></a>
    [Coulouris01] G. Coulouris, J. Dollimore, T. Kindberg, Distributed Systems, Concepts and Design, Pearson Education, 2001.
  </p><p class="bibliomixed"><a name="Gamma95"></a>
    [Gamma95] E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns, Elements of Reusable Object Oriented Software, 1995.
  </p><p class="bibliomixed"><a name="Stevens99"></a>
    [Stevens99] W. R. Stevens, Unix Network Programming (Volume 1), Pearson Education 1999.
  </p><p class="bibliomixed"><a name="Stevens99b"></a>
    [Stevens99b] W. R. Stevens, Unix Network Programming (Volume 2), Pearson Education 1999.
  </p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
