Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't open existing semaphore from another process C++

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading