我正在为更大的软件开发一个小型服务器循环,但它不能像我希望的那样工作。
当用户键入“.quit”时,我希望软件停止此线程服务器循环:
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;
}
我按以下方式启动线程:
serverThread = boost::shared_ptr<boost::thread>( new boost::thread(boost::bind( &myClass::startServer, this )) );
但我在停止“服务器”方面遇到了问题。无论我是否中断线程,关闭套接字和/或接受器,或者只是破坏程序Boost会抛出错误:
Bad file descriptor
它不会每次都发生,但经常发生,我想解决这个问题而不是忽略它。
你能帮我解决这个问题 clean 吗?
答案 0 :(得分:2)
通常,服务器使用异步方法编写
async_accept
async_read
async_write
在这种情况下,关闭所有挂起的异步操作的建议技术是stop io_service
的事件处理循环。请注意,您应该特别注意~io_service
documentation
描述的破坏序列 以上允许程序简化 他们的资源管理使用 的shared_ptr&LT;取代。对象的位置 寿命与a的寿命有关 连接(或其他一些序列) 异步操作),一个shared_ptr 将对象绑定到 所有异步处理程序 与之相关的操作。
根据您发布的问题所在的有限代码对我来说并不明显,我建议发布更多代码或运行valgrind下的内容,因为它很可能会暴露一些问题。
我几天前回答了similar question您可能会发现有用的