asio 0.3.7 Home | Reference | Tutorial | Examples | Design
Examples

http/server/posix_main.cpp

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