Detaching a native socket from Boost.ASIO's socket class

那年仲夏 提交于 2019-12-01 17:33:37

Answering my own question.

Windows has a WSADuplicateSocket function, which can be used to duplicate the native socket. The underlying socket will remain open until all descriptors for this socket are deallocated.

http://msdn.microsoft.com/en-us/library/ms741565(VS.85).aspx

shoumikhin

For Mac OS X do the following (for Linux it isn't hard to modify, just notice the very idea):

  1. Wrap socket in a shared_ptr, so that it won't close when passing into different routines and keep it alive (at least one reference should always exist);
  2. Get a native descriptor with socket.native();
  3. Remove it from kqueue:

    struct kevent event;
    EV_SET(&event, descriptor, EVFILT_READ, EV_DELETE, 0, 0, 0);  //or EVFILT_WRITE
    
  4. And make it blocking if needed:

    fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) & ~O_NONBLOCK);
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!