https://github.com/gongluck/Windows-Core-Program.gitc++
//第3章 內核對象.cpp: 定義應用程序的入口點。 // #include "stdafx.h" #include "第3章 內核對象.h" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { SECURITY_ATTRIBUTES sa = { 0 }; sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = nullptr; sa.bInheritHandle = TRUE;//可被繼承 HANDLE hMutex = CreateMutex(&sa, FALSE, nullptr); SetHandleInformation(hMutex, HANDLE_FLAG_INHERIT, 0);//關閉可繼承 SetHandleInformation(hMutex, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);//打開可繼承 HANDLE hMutex2 = CreateMutex(nullptr, FALSE, TEXT("有名的Mutex")); DWORD err = GetLastError(); if (err == ERROR_ALREADY_EXISTS) MessageBox(NULL, TEXT("打開了已經建立的Mutex"), TEXT("CreateMutex"), MB_OK); else MessageBox(NULL, TEXT("建立了新的的Mutex"), TEXT("CreateMutex"), MB_OK); HANDLE hMutex3 = OpenMutex(MUTEX_ALL_ACCESS, TRUE, TEXT("有名的Mutex")); //靈活的(跨進程)句柄複製 HANDLE hMutex4 = nullptr; DuplicateHandle(GetCurrentProcess(), hMutex, GetCurrentProcess(), &hMutex4, 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hMutex);//調用CloseHandle後,句柄表中的對應值就被重置了,hMutex不會指向原來的內核對象(不管此時引用計數是否爲0) hMutex = nullptr;//良好的習慣 CloseHandle(hMutex2); hMutex2 = nullptr; CloseHandle(hMutex3); hMutex3 = nullptr; CloseHandle(hMutex4); hMutex4 = nullptr; system("pause"); return 0; }