how to use NtCreateMutant(Zw) to create a mutex in C++
I want to create a mutex with the kernel function NtCreateMutant
.
I did it like this:
Handle hMutex;
NTSTATUS ntMutex = NtOpenMutant(&hMutex,MUTEX_ALL_ACCESS,false);
But this is the NTSTATUS
value that is returned:
C0000024 STATUS_OBJECT_TYPE_MISMATCH
With the windows API OpenMutex(..)
, it's working just fine...
HANDLE hMutex;
hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "Name");
Hope someone can explain me how to use the native function :)
So I want to do the same as this, but with native functions:
HANDLE hMutex;
hMutex =开发者_运维问答 OpenMutex(MUTEX_ALL_ACCESS, FALSE, "NameOfMyMutex");
if(hMutex == NULL)
{
hMutex = CreateMutex(NULL, FALSE, "NameOfMyMutex");
}
else
{
return FALSE;
}
I hope someone can help me with calling NtOpenMutant
the right way.
Could you please post more code? It's not entirely clear what's going on here just yet, but here are a few thoughts:
1) You start by saying you create your mutex with NtCreateMutant
, but the code you posted is using NtOpenMutant
. Please clarify exactly what you're actually doing here, preferably with a larger code snippet.
2) NtCreateMutant
doesn't take 3 parameters, and NtOpenMutant
does not take a boolean 3rd parameter:
+NTSTATUS SERVICECALL
+NtCreateMutant(OUT PHANDLE MutantHandle,
+ IN ACCESS_MASK DesiredAccess,
+ IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
+ IN BOOLEAN InitialOwner);
+
+NTSTATUS SERVICECALL
+NtOpenMutant(OUT PHANDLE MutantHandle,
+ IN ACCESS_MASK DesiredAccess,
+ IN POBJECT_ATTRIBUTES ObjectAttributes);
It's not clear which you intend to be using, but it would appear regardless of which you meant to use, you may be using it incorrectly.
If you really mean to use NtOpenMutant
, it would seem that your third parameter needs to be an OBJECT_ATTRIBUTES structure, defined HERE to be:
typedef struct _OBJECT_ATTRIBUTES {
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor;
PVOID SecurityQualityOfService;
} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
Keep in mind that the Nt* functions are not exact mirrors of the public and documented Windows API. This seems to be where you're experiencing your issues.
I believe that what you want is to mimmic the code you posted with winapi, i.e. to try to open, and if not exist create.
I recommend you to look at ReactOs and look for the implementation of OpenMutex and CreateMutex
This should give you the answer of how to "translate" the winapi functions to Native ones
精彩评论