开发者

Stopping threaded server loop using Boost::Asio

开发者 https://www.devze.com 2023-02-04 05:18 出处:网络
I am developing a tiny server loop for a bigger software but it doesn\'t work as I want it to do. When the user types in \".quit\" I want the software to stop this threaded server loop:

I am developing a tiny server loop for a bigger software but it doesn't work as I want it to do.

When the user types in ".quit" I want the software to stop this threaded server loop:

开发者_StackOverflow中文版
try {

while (true) {
      acceptor.accept(socket);
      const size_t buffersize = 1024;
      char data[buffersize+1] = {0};
      data[socket.read_some(boost::asio::buffer(data,buffersize))] = '\0'; // Write data & place terminator
      boost::thread asyncWriting(boost::bind( &myClass::writeToFile, this ));
      socket.close();
}

} catch(const boost::system::system_error& e) {
    cout << "Boost System Error: " << e.what() << endl;
}

I start the thread the following way:

serverThread = boost::shared_ptr<boost::thread>( new boost::thread(boost::bind( &myClass::startServer, this )) );

But I have problems stopping the "server". No matter if I interrupt the thread, close the socket and/or the acceptor or just break the program Boost throws the error:

 Bad file descriptor

It doesn't occurs every time but often and I want to fix that issue and not just ignore it.

Can you help me how to shut this down clean?


Typically servers are written using asynchronous methods

  • async_accept
  • async_read
  • async_write

in which case the suggested technique to shutdown all pending asynchronous operations is to stop the io_service's event processing loop. Note that you should pay special attention to the ~io_service documentation

The destruction sequence described above permits programs to simplify their resource management by using shared_ptr<>. Where an object's lifetime is tied to the lifetime of a connection (or some other sequence of asynchronous operations), a shared_ptr to the object would be bound into the handlers for all asynchronous operations associated with it.

It's not obvious to me based on the limited code that you've posted where your problem is, I'd suggest posting more code or running what you have under valgrind as it will most likely expose some problems.

I answered a similar question a few days ago that you might find useful

0

精彩评论

暂无评论...
验证码 换一张
取 消