I’m trying to get existing semaphore from another process. To create semaphore i used:
Semaphore(std::string name, int startState) {
name = "Global\\" + name;
Sem = OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, true, (LPCWSTR)name.c_str());
int s = (startState > 0);
if (Sem == NULL) {
Sem = CreateSemaphore(NULL, s, 1, (LPCWSTR)name.c_str());
}
}
In first process semaphore created correctly. GetLastError() returns 0. In second process, OpenSemaphore returns NULL. And GetLastError() returns 2.
I tried to get semaphore by only "name" – without "Global\", but it got the same result. Help please)
>Solution :
If you ever feel the need to use C-style casting (like in (LPCWSTR)name.c_str()) you should take that as a sign you’re doing something wrong.
Like you do here: std::string is a narrow character (i.e. char) string, while you use the wide characer (wchar_t) functions. That means the names won’t be what you expect.
If you continue using std::string you must use the "ASCII" functions (e.g. CreateSemaphoreA). Otherwise switch to std::wstring which uses wide characters.