I ported my appliction from Windows 7 32-bit to Windows 7 64-bit. I find that the API function OpenSemaphore is always returning zero. This call works well in 32-bit Windows, but not in 64-bit Windows.
When I call GetLastError(), it returns 2.
Also I replaced my OpenSemaphore with the CreateSemaphore function and my application works fine, but I am still confused about why the OpenSemaphore function is failing in 64-bit code.
Can anyone who knows something about this issue please clarify?
Checking the error code when a function fails is a good first step, but you need to make sure you understand what that error code means. The possible error codes returned by the
GetLastErrorfunction are documented here.In this case, you say that the error code is 2. That corresponds to
ERROR_FILE_NOT_FOUND, which meansYou are probably asking yourself: file, what file? Yeah, sometimes understanding the error codes requires a little bit of creative thought. So let’s think about it: what could “file not found” possibly mean with regard to the
OpenSemaphorefunction? Well, one of the parameters is a string that specifies the name of the semaphore to be opened. That’s sort of like a file, right? Close enough to be a good lead!Chances are, then, the value you’re specifying for the
lpNameparameter does not correspond to a valid semaphore. The first thing I’d normally check is the case of the string—the comparisons made with thelpNamevalue are case-sensitive. But since you said it used to work in a 32-bit application, that’s probably not what’s wrong here.The 32-to-64-bit transition does give us another clue, though. Remember that 32-bit and 64-bit applications are very different beasts and are not generally allowed to touch each other. It stands to reason, then, that a 64-bit application would be unable to use a semaphore created by a 32-bit application, and vice versa.
Considering you said that it works if you call
CreateSemaphoreto create a new semaphore, that puts us well on our way to finding an answer. Chances are, the semaphore you’re trying to open with the call to theOpenSemaphorefunction is one created by a 32-bit process, and it therefore can’t be opened or used by a 64-bit process. (Remember, the documentation tells us that “The function succeeds only if some process has already created the semaphore by using theCreateSemaphorefunction”.) If you create a new semaphore in the 64-bit process, you can open and use it without a problem.