技术背景知识
来自《Windows核心编程》
创建自定义段 Section
来自《Windows核心编程》
举例(获取当前总共运行的实例数)
- 创建自定义段并设置属性
#include "stdafx.h"
#include "MFCApplication1.h"
#include "MFCApplication1Dlg.h"
//创建自定义段
#pragma data_seg("MyShare")
volatile long g_nAppInstCount = 0;
#pragma data_seg()
//设置段的属性:RWS, 可读、可写、可共享
#pragma comment(linker, "/SECTION:MyShare,RWS")
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//....
- 访问共享实例
// CMFCApplication1App 初始化
BOOL CMFCApplication1App::InitInstance()
{
//
//略
//
CWinApp::InitInstance();
//g_nAppInstCount加一
InterlockedExchangeAdd(&g_nAppInstCount, 1);
//
//略
//
//弹框显示实例数
CString strMsg;
strMsg.Format(_T("已运行实例个数%ld"), g_nAppInstCount);
AfxMessageBox(strMsg);
CMFCApplication1Dlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
//
//略
//
//g_nAppInstCount减一
InterlockedExchangeAdd(&g_nAppInstCount, -1);
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
- 实例崩溃时,g_nAppInstCount不会减1,但所有实例都终止后,再运行,g_nAppInstCount会重置
- dumpbin.exe查看生成的exe
程序单实例运行的实现
- 使用上文提到的技术,在一个exe的多个实例中可以共享一个g_AppInstCount,只要此值大于0,就说明有实例在运行了。
- CreateMutex创建一个命名的互斥器,名字需要唯一,如果当前已存在,GetLastError会返回ERROR_ALREADY_EXISTS,故可根据这个事实来实现单实例运行。