[英]Got “Bad file descriptor” when use 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 one new thread handle new connection. 我想要一个新线程处理新连接。 But in function "func", the socket is not open and I got "Bad file descriptor".
但是在函数“func”中,套接字没有打开,我得到了“Bad file descriptor”。 I read some examples in the document and web, but they are async.
我在文档和Web中阅读了一些示例,但它们是异步的。 I think it's not necessary for my simple demand.
我认为这对我的简单要求没有必要。
How can I fix the error? 我该如何修复错误? Any help is appreciated
任何帮助表示赞赏
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. 您的套接字是一个临时对象,您将一个reffence传递给它,但该对象超出了范围并在线程处理之前被销毁。 Use
shared_ptr<socket>
or keep them in a container. 使用
shared_ptr<socket>
或将它们保存在容器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.