asio 0.3.8rc3 Home | Reference | Tutorial | Examples | Design
Examples

http/server/posix_main.cpp

Go to the documentation of this file.
00001 //
00002 // posix_main.cpp
00003 // ~~~~~~~~~~~~~~
00004 //
00005 // Copyright (c) 2003-2007 Christopher M. Kohlhoff (chris at kohlhoff dot com)
00006 //
00007 // Distributed under the Boost Software License, Version 1.0. (See accompanying
00008 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
00009 //
00010 
00011 #include <iostream>
00012 #include <string>
00013 #include <asio.hpp>
00014 #include <boost/bind.hpp>
00015 #include "server.hpp"
00016 
00017 #if !defined(_WIN32)
00018 
00019 #include <pthread.h>
00020 #include <signal.h>
00021 
00022 int main(int argc, char* argv[])
00023 {
00024   try
00025   {
00026     // Check command line arguments.
00027     if (argc != 4)
00028     {
00029       std::cerr << "Usage: http_server <address> <port> <doc_root>\n";
00030       std::cerr << "  For IPv4, try:\n";
00031       std::cerr << "    receiver 0.0.0.0 80 .\n";
00032       std::cerr << "  For IPv6, try:\n";
00033       std::cerr << "    receiver 0::0 80 .\n";
00034       return 1;
00035     }
00036 
00037     // Block all signals for background thread.
00038     sigset_t new_mask;
00039     sigfillset(&new_mask);
00040     sigset_t old_mask;
00041     pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
00042 
00043     // Run server in background thread.
00044     http::server::server s(argv[1], argv[2], argv[3]);
00045     asio::thread t(boost::bind(&http::server::server::run, &s));
00046 
00047     // Restore previous signals.
00048     pthread_sigmask(SIG_SETMASK, &old_mask, 0);
00049 
00050     // Wait for signal indicating time to shut down.
00051     sigset_t wait_mask;
00052     sigemptyset(&wait_mask);
00053     sigaddset(&wait_mask, SIGINT);
00054     sigaddset(&wait_mask, SIGQUIT);
00055     sigaddset(&wait_mask, SIGTERM);
00056     pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
00057     int sig = 0;
00058     sigwait(&wait_mask, &sig);
00059 
00060     // Stop the server.
00061     s.stop();
00062     t.join();
00063   }
00064   catch (std::exception& e)
00065   {
00066     std::cerr << "exception: " << e.what() << "\n";
00067   }
00068 
00069   return 0;
00070 }
00071 
00072 #endif // !defined(_WIN32)
asio 0.3.8rc3 Home | Reference | Tutorial | Examples | Design