简体   繁体   中英

Boost ASIO socket consumes file descriptors never cleared

I'm using Boost ASIO sockets for communicating with some remote devices under linux, but i have a problem when the endpoint is not reachable. First of all, here's the portion of code that shows this issue:

try {
   if(mysocket == NULL)
   {
      mysocket = new boost::asio::ip::tcp::socket(io_service);
   }
   mysocket->connect(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("192.168.0.12"), 1));
   printf("connected\n");
   return 0;
}
catch (std::exception &e)
{
   boost::system::error_code ec;
   mysocket->close(ec);
   delete mysocket;
   mysocket = NULL;
   printf("not connected %s\n", e.what());
}

By using this piece of code inside my class I get an increasing number of file descriptors of type eventfd, until all the available fds are used and the application crashes. Is there any problem with the code above? Why boost is not closing the file descriptors? I even delete the socket! Thanks in advance!

Like others said, just don't write new and delete , and you know you didn't mess it up yourself.

In particular your misguided

mysocket->close(ec);

will throw because the socket isn't open in the first place, so you never reached delete .

However, mysocket can be automatically destructed at the end of scope: The entire code can be simplified to:

#include <boost/asio.hpp>
#include <iostream>
namespace ba = boost::asio;
using ba::ip::tcp;

int main() {
    ba::io_context io_service;
    try {
        tcp::socket mysocket(io_service);
        mysocket.connect({ba::ip::address::from_string("192.168.0.12"), 1});
        std::cout << "Connected to " << mysocket.remote_endpoint() << "\n";
    }
    catch (boost::system::system_error const& se) {
        std::cout << "System error: " << se.code().message() << "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM