Link to home
Start Free TrialLog in
Avatar of ViniT
ViniT

asked on

Semaphores question

Im creating a semaphore with a certain name.
Then Im trying to create it again with the same parameters.
CreateSemaphore creates two semaphores, while it should return me the previous semaphore handle. Why is this happening?
I am supposed to get a last error of ERROR_ALREADY_EXISTS, but Im not...

These are my declarations:
--------------------------
Private Declare Function CreateSemaphore Lib "kernel32" Alias "CreateSemaphoreA" (ByRef lpSemaphoreAttributes As SECURITY_ATTRIBUTES, ByVal lInitialCount As Long, ByVal lMaximumCount As Long, ByVal lpName As String) As Long
Private Type SECURITY_ATTRIBUTES
        nLength As Long
        lpSecurityDescriptor As Long
        bInheritHandle As Long
End Type

This is the subroutine:
-----------------------
 Dim sec As SECURITY_ATTRIBUTES
 sec.bInheritHandle = 1&
 sec.nLength = Len(sec)
 Dim Hsem As Long
 Hsem = CreateSemaphore(sec, 0, 1, "Hello")
 msgbox Hsem
 Hsem = CreateSemaphore(sec, 0, 1, "Hello")
 msgbox Hsem
----------------

Help please! :-)
Avatar of danlevans
danlevans

When you CreateSemaphore on an already open handle of the same name, you get both a valid handle return and the error ERROR_ALREADY_EXISTS . Check your error codes even if you get a valid handle back. In this case it should be the same handle as you got on the first call.

Have fun

Dan
Avatar of ViniT

ASKER

Im sorry, but GetError always returns me Operation succeeded!
Avatar of ViniT

ASKER

Nothing works!
Im using the same parameters in a sequent call to CreateSemaphore and it returns me two different handles!!! why is this happening?!
I tried your code, and I also got two different values for hsem.
BUT
err.LastDllError gives me number 183 (already exists) on the second call

If you call GetLastError() it is possible that it returns 0 because under the hood VB is making more calls to the WinAPI, so be sure to use err.LastDllError
Avatar of ViniT

ASKER

Still, why is it returning the a new number for the semaphore?
The documentation says:

If the function succeeds, the return value is a handle to the semaphore object. If the named semaphore object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS.

It does not say it has to be the same handle, you just get a handle to the same semaphore. Also if you call OpenSemaphore() you get a different handle to the same object. Do you want the same handle call DuplicateHandle.

(With API calls you must always check the return code or GetLastError)

ASKER CERTIFIED SOLUTION
Avatar of corvanderlinden
corvanderlinden

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ViniT

ASKER

Thanks.