6
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 one new thread handle new connection. But in function "func", the socket is not open and I got "Bad file descriptor". I read some examples in the document and web, but they are async. I think it's not necessary for my simple demand.

How can I fix the error? Any help is appreciated

leezii
  • 127
  • 1
  • 1
  • 5
  • Possibly this happens because main thread executes accept(socket) at the same time, as another thread tries to work with the socket. Passing by reference, you are working with the same socket instance. – Alex F Sep 13 '12 at 08:53
  • @AlexFarber I don't think that. Because I use only one client to connect the server , there is only one connection. – leezii Sep 13 '12 at 09:02
  • But at the same time, when one client tries to work with the socket, main thread applies accept operator to the same socket. – Alex F Sep 13 '12 at 09:29
  • Actually, the instance is destroyed in every loop.. Try to add for(;;) after creating thread - does it work now? – Alex F Sep 13 '12 at 09:35
  • @AlexFarber you're right. add for(;;) and it can work. Thanks. – leezii Sep 13 '12 at 09:47
  • Well, it is not real solution, just test. Follow the answer posted by Slava Zhuyko. – Alex F Sep 13 '12 at 09:53

1 Answers1

11

Your socket is a temporary object, you pass a reffence to it but the object is going out of the scope and being destroyed before the thread process it. Use shared_ptr<socket> or keep them in a container.

Slava Zhuyko
  • 691
  • 4
  • 12