Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

windows 动态库中使用coost日志库导致程序不能正常退出 #294

Open
sdaereew opened this issue Jan 13, 2023 · 9 comments
Open
Labels

Comments

@sdaereew
Copy link

Windows10 64 位环境

生成一个dll,导出如下函数
DLLLOG_API void LogMessage()
{
LOG << "111";
}

生成一个exe,代码如下
typedef void (LogMessageFun)();
int main(int argc, wchar_t
argv[])
{
HINSTANCE hinst = LoadLibrary(L"DllLog.dll");
if (hinst != nullptr)
{
LogMessageFun pLog = (LogMessageFun)GetProcAddress(hinst, "LogMessage");

	pLog(); // 注释掉可以正常退出

	FreeLibrary(hinst);
}
return 0;

}

程序不能正常退出.

@sdaereew
Copy link
Author

*被吃掉了,正确代码如下
image

@idealvin
Copy link
Owner

试试在 FreeLibrary 之前调用 log::exit()

@sdaereew
Copy link
Author

我测了下,调用log::exit()是可以正常退出的. 但是这个方案有个问题,我这里实现的是一个插件,插件使用了coost的日志功能.主程序是其他公司的产品,没有源代码.

@idealvin
Copy link
Owner

我测了下,调用log::exit()是可以正常退出的. 但是这个方案有个问题,我这里实现的是一个插件,插件使用了coost的日志功能.主程序是其他公司的产品,没有源代码

log::exit()封装到你的 dll 里,供用户调用就可以了

@idealvin idealvin added the faq label Jan 16, 2023
@sdaereew
Copy link
Author

这个方案不可行,主程序是国外公司的产品,全世界有很多开发者在上面做二次开发,不会单独针对我这个插件做修改.有没有其他的方案,我这里修改就可以解决这个问题?

@sdaereew
Copy link
Author

image
试了下不行,exit在这里调用不能正常退出.

@sdaereew
Copy link
Author

析构函数里面调用也不行.
另外发现使用xmake构建的coost库,调试版本dll和对应的pdb不匹配,vs2019调试的时候不能加载pdb文件.release版本则没有这个问题.
构建方法: coost根目录下执行 xmake -a

@idealvin idealvin changed the title 3.0.0版本日志库导致程序不能正常退出 windows 动态库中使用coost日志库导致程序不能正常退出 Jan 16, 2023
@idealvin
Copy link
Owner

@sdaereew

程序退出时卡住应该与之前遇到的一个坑是一样的:

windows dll动态库卸载时,线程的运行时先被卸载(当时查到的资料好像是这样,没记错的话),导致线程失去作用、无法被唤醒,dll中等待线程退出的代码将永远无法响应(coost/log中是程序退出时等待写日志的线程退出,调用log::exit()会退出该线程)。

这样就能解释,为什么在调用FreeLibrary卸载dll前调用 log::exit(),程序就不会卡住。

windows上使用动态库很容易踩到这个坑,比较安全的做法是在 dll 卸载前退出所有线程。

后续可能增加一些探测性代码,若线程长时间没有反应,就不再等待

@sdaereew
Copy link
Author

好的,感谢回复.有时间的话我也研究下这个问题.

@idealvin idealvin closed this as completed Nov 7, 2023
@idealvin idealvin reopened this Dec 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants