Got a "Bad file descriptor" when using boost :: asio and boost :: thread

int func(boost::asio::ip::tcp::socket &socket)
{
    boost::system::error_code ec;
    socket.write_some(boost::asio::buffer("hello world!"), ec);
    cout << socket.is_open() << endl;
    if(ec)
    {
        cout << boost::system::system_error(ec).what() << endl;
    }
    return 0;
}

int main(int argc, char* argv[])
{
    using namespace boost::asio;
    io_service iosev;
    ip::tcp::acceptor acceptor(iosev, ip::tcp::endpoint(ip::tcp::v4(), 1000));

    while(1)
    {
        ip::tcp::socket socket(iosev);
        acceptor.accept(socket);
        boost::thread t = boost::thread(func, boost::ref(socket));
    }
    return 0;
}

I want the new thread to handle the new connection. But in the func function, the socket is not open, and I got a Bad file descriptor. I read a few examples in the document and on the Internet, but they are asynchronous. I think this is not necessary for my simple requirement.

How can I fix the error? Any help is appreciated

+5
source share
1 answer

Your socket is a temporary object, you give it a reference, but the object goes out of scope and is destroyed before the thread processes it. Use shared_ptr<socket>or store them in a container.

+10
source

All Articles