The previous article is very simple and easy to understand. However, in C ++, you still need to encapsulate the code that can be used in multiple projects.
The following cancels the global variable, creates a server class, provides the run function, and the server object also listens to semaphores to exit elegantly.
# Include <cstdlib> # include <boost/ASIO. HPP> # include <boost/bind. HPP> # include <iostream> using namespace boost; using namespace boost: ASIO; using namespace STD; Class server {public: Server (io_service & S): IO _ (s ), signals _ (s) {signals _. add (SIGINT); SIGNALS _. add (sigterm); # If defined (sigquit) signals _. add (sigquit); # endif signals _. async_wait (boost: BIND (& server: Stop, this);} void run () {IO _. run ();} PRIVATE: void stop () {cout <"X" <Endl; IO _. stop () ;}private: io_service & IO _; Boost: ASIO: signal_set signals _ ;}; int main (INT argc, char ** argv) {io_service S; server server (s); server. run (); Return 0 ;}
Run the program and kill the process. The result is that the program exits after X is displayed.