问题
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.
回答1:
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.
回答2:
MSDN says:
Therefore, the entry-point function can call functions in Kernel32.dll that do not load other DLLs. [...] Unfortunately, there is not a comprehensive list of safe functions in Kernel32.dll.
Then it expands the statement explaining that more complicated APIs (CreateProcess included) might involve usafe API calling:
Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.
This is what stands behind best practices advise to not call CreateProcess. It is out of your control whether CreateProcess will or will not load other DLLs. In your control is to avoid unsafe API call and create process later.
来源:https://stackoverflow.com/questions/26754014/why-createprocess-must-not-be-called-from-a-dllmain-function