CreateMutex 和 OpenMutex 返回 NULL

发布于 2024-12-22 17:02:50 字数 674 浏览 2 评论 0原文

我正在编写一个具有共享内存的应用程序,并使用名称上适当的 "Local\" 前缀创建命名互斥体。但是,每次调用 CreateMutex 函数来创建句柄时,我都会得到 NULL 返回值。之后我什至尝试调用 OpenMutex 并得到 NULL 返回。

GetLastError() 函数返回 6,这意味着 ERROR_INVALID_HANDLE。我相信在任何进程中第一次尝试创建此命名互斥体时都会发生这种情况。我在包含一些 MFC 组件后包含了 windows.h,并在应用程序的其他地方使用了 CMutex;所以我不知道这是否是一个问题。我始终为前两个参数传递 NULLFALSE,并且我使用的是 Windows XP。

这是我的代码的作用的摘要:

char to_name[16] = "Local\\to_1";
d_mutex_to_h = CreateMutex(NULL, FALSE, to_name);

if (d_mutex_to_h == NULL)
{
   d_mutex_to_h = OpenMutex(NULL, FALSE, to_name);
}

I'm writing an application with shared memory and am creating named mutexes with the appropriate "Local\" prefix on the name. However, every time I call the CreateMutex function to create the handles, I get a NULL return value. I even try calling OpenMutex after that and get a NULL return.

The GetLastError() function returns 6 which means ERROR_INVALID_HANDLE. I believe that this happens on the first attempt to create this named mutex in any process. I included windows.h after including some MFC components and am using CMutex elsewhere in the application; so I don't know if this is a problem or not. I am passing NULL and FALSE for the first two parameters always and am using Windows XP.

This is a summary of what my code does:

char to_name[16] = "Local\\to_1";
d_mutex_to_h = CreateMutex(NULL, FALSE, to_name);

if (d_mutex_to_h == NULL)
{
   d_mutex_to_h = OpenMutex(NULL, FALSE, to_name);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戏蝶舞 2024-12-29 17:02:50

来自 CreateMutex< 的 MSDN 文档/a>:

如果 lpName 与现有事件、信号量、可等待计时器、作业或文件映射对象的名称匹配,则该函数将失败,并且 GetLastError 函数将返回 ERROR_INVALID_HANDLE。发生这种情况是因为这些对象共享相同的命名空间。

尝试使用 WinObj 来查看是否存在同名的非互斥对象。

From the MSDN documentation for CreateMutex:

If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace.

Try using WinObj to see if there's a non-mutex object with the same name.

秋叶绚丽 2024-12-29 17:02:50

CreateMutex()LPCTSTR 作为最后一个参数。这是一个宏,如果定义了 UNICODE,则为 LPCWSTR,否则为 LPCSTR。但是,您正在传递一个指向 char 字符串的指针。如果您的程序是使用定义的 UNICODE 进行编译的,则可能会导致问题。

尝试这段代码,看看它是否改变了什么:

d_mutex_to_h = CreateMutex(NULL, FALSE, _T("your_mutex_name_here"));

CreateMutex() takes LPCTSTR as last argument. This is a macro which is LPCWSTR if UNICODE is defined, and LPCSTR otherwise. However you are passing a pointer to char string. It may cause a problem if your program is compiled with UNICODE defined.

Try this code and see if it changes anything:

d_mutex_to_h = CreateMutex(NULL, FALSE, _T("your_mutex_name_here"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文