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 09:13:31 am
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[106775]
2D Rotated Rectangles Collision Detection[79918]
Keyboard Hook[69063]
UDP[53058]
HTTP Proxy[36303]

::Top 5 Samples::
2D ColDet Rotated Rectangles[10638]
PS2 Mouse Driver[6122]
Wave Format Player[5005]
Reading FAT12[4893]
CodeGuru[4579]


All rights reserved to RageStorm © 2009