我通过Dllmain()
API在CreateThread()
中创建了一个新线程,它不涉及线程同步,它只是一个单独的线程。
Dllmain()
调用WaitForSingleObject(funcThread, INFINITE);
强制主线程等待funcThread
完成。
然后我动态链接这个Dllmain()
,但是结果显示funcThread()
提前完成了。我知道添加一个系统暂停是可行的,但是您有一些方法可以使它只通过更改Dllmain()
文件来工作吗?
奇怪的是,当更改printf()
和OutputDebugStringW()
的顺序时,结果是不同的。
targetFuction.exe
#include <Windows.h>
#include <iostream>
int main() {
HINSTANCE hModule = LoadLibrary(L"testDllmain.dll");
return 0;
}
testDllmain.dll
#include <Windows.h>
#include <iostream>
DWORD WINAPI function(LPVOID lpParam) {
for (int i = 0; i < 100; i++) {
printf("%d \n", i);
}
return 0;
}
HANDLE funcThread;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
funcThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
function, // thread function name
NULL, // argument to thread function
0, // use default creation flags
NULL);
OutputDebugStringW(L"attach process!\n");
printf("attach process!\n");
break;
case DLL_PROCESS_DETACH:
WaitForSingleObject(funcThread, INFINITE);
OutputDebugStringW(L"detach process!\n");
printf("detach process!\n");
// printf("detach process!\n");
// OutputDebugStringW(L"detach process!\n");
break;
case DLL_THREAD_ATTACH:
printf("attach thread!\n");
OutputDebugStringW(L"attach thread!\n");
break;
case DLL_THREAD_DETACH:
OutputDebugStringW(L"detach thread!\n");
printf("detach thread!\n");
break;
}
return TRUE;
}
输出:
OutputDebugStringW()
先于printf()
printf()
先于OutputDebugStringW()
它还应该打印23到99和detach process
消息,但它们都丢失了。
发布于 2022-06-30 07:21:07
DllMain()
显式地不支持您想要做的事情。
您不应该在DllMain中执行以下任务:
还有更多。
发布于 2022-07-01 08:48:49
根据LoadLibrary,系统卸载一个模块时,它的引用计数达到零或当进程终止(不管引用计数)。然后调用FreeLibrary应该使主线程通过DLL_PROCESS_DETACH
执行。
我试过了,然后问题可能是,主进程总是在等待线程,但是线程永远不会执行。这有风险吗?
编辑:如果线程函数不在释放的动态库中,就没有问题。
https://stackoverflow.com/questions/72811629
复制相似问题