Home
Tutorials
Code Snippets
Code Samples
Downloads
Links

The Blog
Our Projects
About
Contact

::Add RageStorm to Favorites!::

The Blog | Our Projects | Guest Book | About | Contact

 
Code Snippet - Query Semaphore
Author:Arkon
Category:Win32API
File Size:~ 1.20 KB
Uploaded at:15-Jul-06 01:13:31 pm
Description:
  Shows how to query the count of aquires left on the Semaphore using an undocumented API.
  
When using a Semaphore synchronization object
sometimes you would like to know how many "aquires" are left to be done.
Therefore there's the NtQuerySemaphore function which resides in NTDLL.DLL.

typedef struct _SEMAINFO {
UINT Count;
UINT Limit;
} SEMAINFO, *PSEMAINFO;

#define SEMAQUERYINFOCLASS 0
typedef long (WINAPI *NtQuerySemaphorePtr)(HANDLE Handle, UINT InfoClass, PSEMAINFO SemaInfo, UINT InfoSize, PUINT RetLen);
NtQuerySemaphorePtr NtQuerySemaphore = NULL;
UINT WINAPI QuerySemaphore(HANDLE hSemaphore)
{
SEMAINFO SemInfo;
UINT RetLen;
NtQuerySemaphore(hSemaphore, SEMAQUERYINFOCLASS, &SemInfo, sizeof(SemInfo), &RetLen);
// You can check return value if you like.
return SemInfo.Count;
}

// Init code:
HMODULE g_ntdll = LoadLibrary("ntdll.dll");
NtQuerySemaphore = (NtQuerySemaphorePtr)GetProcAddress(g_ntdll, "NtQuerySemaphore");

// Usage example:
HANDLE h = CreateSemaphore(NULL, 4, 5, "mysem");
WaitForSingleObject(h, 0);
WaitForSingleObject(h, 0);
WaitForSingleObject(h, 0);
printf("Semaphore has been acquired %d times.\n", 4-QuerySemaphore(h));
ReleaseSemaphore(h, 3, NULL);
CloseHandle(h);

// Destroy code:
FreeLibrary(g_ntdll);
User Contributed Comments(None)
NOTE:
Comments that will hurt anyone in any way will be deleted.
Don't ask for features, advertise or curse.
If you want to leave a message to the author use the contacts,
if you have any question in relation to your comments please use the forum.
Comments which violate any of these requests will be deleted without further
notice. Use the comment system decently.

Post your comment:
Name:
email:
Comment:
::Top 5 Tutorials::
Embedded Python[117069]
2D Rotated Rectangles Collision Detection[88994]
Keyboard Hook[77338]
UDP[65887]
HTTP Proxy[41225]

::Top 5 Samples::
2D ColDet Rotated Rectangles[11562]
PS2 Mouse Driver[6960]
Wave Format Player[5793]
Reading FAT12[5621]
CodeGuru[5361]


All rights reserved to RageStorm © 2009