vendredi 5 juin 2020

Sometimes, the asio::tcp::socket object gets closed automatically before calling shutdown/close

Once in 5 times, I get this "Bad file descriptor"error when I am attempting to shutdown or close the asio::ip::tcp::socket object. The following is the function to close the acceptor and socket.

void close_server()
{
    acceptor_instance.close(error_code);
    if (error_code)
    {
        std::cerr << "close_server(): acceptor::close()" << "Error: " << error_code.message() << std::endl;
    }        
    if(socket_instance.is_open())
    {
        socket_instance.shutdown(asio::ip::tcp::socket::shutdown_both, error_code);
        if (error_code)
        {
            std::cerr << "close_server(): socket::close()" << "Error: " << error_code.message() << std::endl;
        }
        socket_instance.close(error_code);
        if (error_code)
        {
            std::cerr << "close_server(): socket::close()" << "Error: " << error_code.message() << std::endl;
        }
    }
    else
    {
        std::cerr << "close_server(): socket_instance is already CLOSED" << std::endl;
    }
}

Sometimes the socket_intance.is_open() fails. Attempting to call the socket.shutdown() or socket.close() without checking if the socket is open, gives "Bad file descriptor" error, that means the socket was already closed.

How to identify the cause?

How to know when it was closed?

Aucun commentaire:

Enregistrer un commentaire