WSACleanup and atExit

Is it possible to register WSACleanup through the atExit function? We have several applications that can end at different points in the code, so we would like to avoid using WSACleanup everywhere, using code. We are currently calling WSAStartup / WSACleanup through DllMain, since we have a dll that is used by all of these applications. However, Microsoft strongly advises against using WSAStartup / WSACleanup through DllMain, as this may cause deadlocks. We can port WSAStarup from DllMain and call this at one point in the code for all applications before they access the Windows socket library. And, as soon as we call WSAStartup, we would like to use the atExit function to register a WSACleanup call. Anyone have experience with this approach? Thanks!

+6
c ++ atexit winsock wsastartup
source share
3 answers

If you have a multi-threaded application and some of the streams are still connected, applications on the other end may not like how the connection ends. Therefore, it is preferable to close all messages in an orderly manner before main () exits, and when you do, you can simply call WSACleanup.

+4
source share

I agree that the RAII approach is favorable.

However, the warning word: atExit, mixed with dll and handles, is broken into windows. Unfortunately, this also affects RAII, as it is implemented using atExit handlers using the C ++ runtime.

The order in which atexit handlers are called in windows is:

  • Some output is called or main () leaves the scope
  • The atexit handlers defined in the process are called.
  • all descriptors are destroyed.
  • The atexit handlers defined in the dll are called.

It does not matter if the atexit handlers are registered in the dll before the process handlers, the process handlers are called first, and the descriptors are destroyed before the dll handlers are called. This leads to win32 exceptions when the cleanup code is called, since all descriptors owned by the dll are no longer valid.

This effect code that contains descriptors for streams, mutexes, files, sockets, etc. If they are allocated in the dll, they must be cleared before calling the call or not.

By the way, I am not an anti-window, if I am mistaken, or anyone knows about this, I would like to know, as this causes me incalculable pain when cleaning the application. I realized that this would be debugging output processing in the C ++ runtime, after receiving win32 exceptions on application exit.

I had to remove all calls to exit my code. Now I have made sure that no static data in the dll controls the handle. All static pens are controlled by objects that collapse when the main part goes outside the area.

+2
source share

Well, I think atExit should not be used. You must follow the RAII principle of wrapping the initialization and destroying the socket library in the class.

+1
source share

All Articles