How do I know the .exe that loaded my dll is about to exit?

I have a dll which is actually a com service that is registered and then loaded by another .exe process. I would like, when the user exits the .exe, to perform some steps of closing the resources from my DLL before it's too late. I tried to intercept the DLLPROCESSDETACH or DLLTHREADDETACH from the DllMain of my DLL, but it seems that when it gets there, it's already too late when the threads started by my DLL (what do I need to do the closing steps) are already stopped ?! Of course, I am not in control of the .exe code, otherwise I would call a call from there to do those clean closing steps before it exits. I can only work with the DLL itself. It seems like DllCanUnloadNow or DllUnregisterServer is called as well.

Is there any work around for this situation?

Thank you for any inputs.

+2


source to share


3 answers


You can write a static object with dtor, dtor will be called as soon as the service exits and the program runtime will be unloaded.



struct CDtorMyDll
{
  ~CDtorMyDll
  {
    // do cleanup stuff here.
  }
};

static CDtorMyDll dtorMyDll;

      

+1


source


Silly question: why do you need to run threads you created? They will still be destroyed and all resources used by the process will be cleaned up.



Having said that, if your object is indeed a COM object, you can add code to your DllCanUnloadNow call to determine if there are any outstanding instances of your objects, and if not, clean up your resources. This won't work if the process leaks references to your objects or doesn't call CoUninitialize, but if the process your object is in follows the rules, it gets a chance to clean up before the process exits.

0


source


Trying to do this through DllMain or the destructor will result in weirdness because the DLL itself will be in a weird state (read all of Raymond Chen's articles on DllMain and you'll see).

The real solution here is to have explicit functions MyDllInitialize () and MyDllTeardown () called before the process exits.

0


source







All Articles