title: standard way to perform a clean shutdown with Boost.Asio
body: <p>I'm writing a cross-platform server program in C++ using Boost.Asio.  Following the HTTP Server example on <a href="http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/examples.html" rel="noreferrer" title="Examples">this page,</a> I'd like to handle a user termination request without using implementation-specific APIs.  I've initially attempted to use the standard C signal library, but have been unable to find a design pattern suitable for Asio.  The <a href="http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/example/http/server/win_main.cpp" rel="noreferrer" title="Boost C++ Libraries - doc/html/boost_asio/example/http/server/win_main.cpp">Windows example's</a> design seems to resemble the signal library closest, but there's a race condition where the console ctrl handler could be called after the server object has been destroyed.  I'm trying to avoid undefined behavior as specified by the C++ standard.</p>
  
  <p>Is there a standard (and correct) way to stop the server?</p>
  
  <p>To illustrate problems with using the C signal library:</p>
  
  <pre><code>#include &lt;csignal&gt;
  #include &lt;functional&gt;
  #include &lt;boost/asio.hpp&gt;
  
  using std::signal;
  using boost::asio::io_service;
  
  namespace
  {
      std::function&lt;void ()&gt; sighandler;
  }
  
  extern "C"
  {
      static void handle_signal(int);
  }
  
  void handle_signal(int)
  {
      // error - undefined behavior
      sighandler();
  }
  
  int main()
  {
      io_service s;
      sighandler = std::bind(&amp;io_service::stop, &amp;s);
      auto old_sigint = signal(SIGINT, &amp;handle_signal);
      if (old_sigint == SIG_IGN)
          // race condition?  raise SIGINT before I can set ignore back
          signal(SIGINT, SIG_IGN);
      auto old_sigterm = signal(SIGTERM, &amp;handle_signal);
      if (old_sigterm == SIG_IGN)
          // race condition?  raise SIGTERM before I can set ignore back
          signal(SIGTERM, SIG_IGN);
      s.run();
      // reset signals so I can clear reference to io_service
      if (old_sigterm != SIG_IGN)
          signal(SIGTERM, SIG_DFL);
      if (old_sigint != SIG_IGN)
          signal(SIGINT, SIG_DFL);
      // clear reference to io_service, but can I be sure that handle_signal
      // isn't being executed?
      sighandler = nullptr;
      // io_service is destroyed
  }
  </code></pre>