winapicreateprocessdllmain

Why CreateProcess must not be called from a DllMain function?


I've read in several sources that CreateProcess must not be called from a DllMain function.

CreateProcess :

Do not call CreateProcess from a DllMain function. This causes the application to stop responding.

Dynamic-Link Library Best Practices:

You should never perform the following tasks from within DllMain: Call CreateProcess. Creating a process can load another DLL.

Question

Why is that? it states that it causes the application to stop responding but this is just a symptom. what is the real reason?

The reason I'm asking is that I tried creating a process from a DllMain function and it sees to work just fine.


Solution

  • DllMain executes whilst the loader lock is held. As explained by the documentation you referenced, CreateProcess may result in a DLL being loaded. And that can lead to dead lock on the loader lock. The dead lock occurs because the loader lock is already held.

    The documentation is clear. Don't call CreateProcess from DllMain. The standard way to get things done from DllMain is to create a thread to do the work. Although you must not wait on that thread because that leads to exactly the same dead lock.