0
votes

I created a TCP client that has a boost asio tcp socket and who makes asynchronous read:

class TCPClient {
 public:
  TCPClient(boost::asio::io_service& io_service)
    : socket_(io_service) {
    // Connect
    [...]
    // Asynchronous read
    socket_.async_read_some(boost::asio::buffer(buffer, buffer.size()),
                            boost::bind(&TCPClient::handlerRead,
                                        this,
                                        placeholders::error,
                                        placeholders::bytes_transferred));
  }
  ~TCPClient() {}

  void handlerRead(const boost::system::error_code& ec, uint32_t bytes) {
    if (!ec) {
      // process
      [...]
      socket_.async_read_some(
        boost::asio::buffer(buffer, buffer.size()),
        boost::bind(&TCPClient::handlerRead,
                    this,
                    placeholders::error,
                    placeholders::bytes_transferred));
  }

  int getSocketFd() {
    return socket_.native_handle();
  }

 private:
  boost::asio::tcp::socket socket_;
};

This is working fine. But when I am putting this in a thread:

boost::asio::io_service io_service;
auto client = new TCPClient(io_service);
std::thread{[&io_service](){ io_service.run(); }};

... and getting file descriptor of the socket:

int socket_fd = client->getSocketFd();

Because I want this part of the program to use the TCP/IP socket to send packets on this socket. But then, my program is segfaulting with this error:

#1  0x000000000041fab0 in boost::asio::detail::task_io_service_operation::complete(boost::asio::detail::task_io_service&, boost::system::error_code const&, unsigned long) ()
#2  0x0000000000420b5f in boost::asio::detail::task_io_service::do_run_one(boost::asio::detail::scoped_lock<boost::asio::detail::posix_mutex>&, boost::asio::detail::task_io_service_thread_info&, boost::system::error_code const&) ()
#3  0x00000000004207df in boost::asio::detail::task_io_service::run(boost::system::error_code&) ()
#4  0x0000000000420eab in boost::asio::io_service::run() ()

Do you have any clue on what is happening here ?

1
You are right. How stupid I am!klaus

1 Answers

1
votes

You define io_service on the stack in one thread. But you access it from a different thread. It seems that the object is no longer alive at the moment of .run() call.

Moving it to the heap is one possibility. Anyway some deeper analysis of the code, relationship between components and liveness is needed.