Home > Software engineering >  Can't open existing semaphore from another process C
Can't open existing semaphore from another process C

Time:12-20

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)

CodePudding user response:

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 "ANSI" functions (e.g. CreateSemaphoreA). Otherwise switch to std::wstring which uses wide characters.

CodePudding user response:

@SomeProgrammerDude's answer explains the cause of the error you are seeing (character encoding mismatch).

I just want to point out that after fixing that problem, your code still has a race condition in it.

If you want to open an existing semaphore (or any other kind of named kernel object), and create it if it doesn't exist, then don't bother wasting time opening it, just create it unconditionally, eg:

Semaphore(std::string name, int startState) {
    name = "Global\\"   name;
    int s = (startState > 0);
    Sem = CreateSemaphoreA(NULL, s, 1, name.c_str());
}

If the object already exists, you will get a handle to the existing object. Otherwise you will get a handle to a new object. GetLastError() can be used to tell you whether the object already existed or was created anew, if needed.

  • Related