note : test Mutex

来源:互联网 发布:税务师考试含金量 知乎 编辑:程序博客网 时间:2024/06/04 19:29
// testMutex.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <windows.h>#define CLOSE_MUTEX_SAFE(h) \{ \    if (NULL != (h)) \    { \    ::ReleaseMutex((h)); \    ::CloseHandle((h)); \    (h) = NULL; \    } \}void __cdecl fnGlobalClean();HANDLE  g_hMutexFirst = NULL;int _tmain(int argc, _TCHAR* argv[]){    DWORD   dwRc = 0;    HANDLE  hMutex = NULL;    atexit(fnGlobalClean);    while (1)    {        ::Sleep(1000);        /// 创建有名称的互斥量:        /// CreateMutexExW 总是成功的, 要看 GetLastError        /// 在本进程执行, 总是得到新的句柄        /// 在其他进程执行,         /// 如果是先执行, 返回新建的句柄        /// 如果是后执行, 返回上一个进程创建的句柄        hMutex = ::CreateMutexExW(            NULL,             L"Mutex_testMutex",             CREATE_MUTEX_INITIAL_OWNER,             MUTEX_ALL_ACCESS);        dwRc = GetLastError();        if (NULL != hMutex)        {            _tprintf(L"CreateMutexExW OK, hMutex = 0x%p, dwRc = 0x%X\r\n",                 hMutex,                 dwRc);            if (ERROR_ALREADY_EXISTS == dwRc)            {                CLOSE_MUTEX_SAFE(hMutex);                _tprintf(                    L"ERROR_ALREADY_EXISTS == dwRc, "                    L"CloseHandleSafe\r\n\r\n");            }            else            {                g_hMutexFirst = hMutex;            }        }    }    return 0;}void __cdecl fnGlobalClean(){    _tprintf(L"fnGlobalClean\r\n");    CLOSE_MUTEX_SAFE(g_hMutexFirst);    /// watch point    ::MessageBoxExW(        NULL,        L"退出前的处理",         L"testMutex",         MB_OK | MB_ICONINFORMATION,         MAKELANGID(LANG_CHINESE_SIMPLIFIED, SUBLANG_CHINESE_SIMPLIFIED));}


原创粉丝点击