1

I'm trying to create a C++ daemon that is capable of asynchronously sending/receiving requests/responses as packets over the network. It should communicate with clients (outwards-facing message API) and other daemons (inter-server messages)

I'm currently looking at boost::asio, specifically http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tutdaytime6/src.html as a starting point that seems to be running a server capable of handling async. send and receive.

My question is, could this server be run alongside (in the background) a command loop, such as a process responding to user input (e.g. shell)? The daytime server program provided seems to block on the line io_service.run();

Would this require a forked or separate threaded server?

jest jest
  • 125
  • 1
  • 2
  • 8
  • Take a look at [io_service::poll](http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/io_service/poll/overload1.html) and [poll_one](http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/io_service/poll_one/overload1.html) member functions - you can interleave these calls with a 3-d party message loop. – Igor R. Nov 20 '17 at 06:00
  • Or just use stream support to read stdin in the first place https://stackoverflow.com/a/23721159/85371 – sehe Nov 20 '17 at 13:56

1 Answers1

1

You simply create a thread member variable, and let the io_service run on the thread. You can process all the process-input in your main-thread, and give your server-class-variable some work to do.

std::thread ioThread;
ioThread = std::thread([this]() { io_service.run(); });

Do not forget to join the thread later and stop the io_service.

io_service.stop();
if (ioThread.joinable())
    ioThread.join();
Blacktempel
  • 3,935
  • 3
  • 29
  • 53