OpenFileMapping got error code 2 unpredictably

D T 20 Reputation points
2023-05-25T13:20:17.71+00:00

I'm creating named shared memory following https://learn.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory

I create the shared memory in process A then access it immediatly from process B, and I got error code 2 (not found) unpredictably when calling

OpenFileMapping

. Sometimes it works, sometimes not.

Do I need to wait for a while before I can access the newly created memory?

You can find source code here:

Process A: https://github.com/DiscreteTom/shremdup

Process B: https://github.com/DiscreteTom/HyperDesktopDuplication

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,422 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 40,286 Reputation points
    2023-05-25T13:47:45.8333333+00:00

    If you are not using any synchronization to ensure that the process that calls OpenFileMapping does not make the call before the process that calls CreateFileMapping has created the shared memory then the described error can occur. Instead of using OpenFileMapping you can use CreateFileMapping in both processes.

    According to Microsoft's documentation at Creating a File Mapping Object "The first process that calls CreateFileMapping creates the file mapping object. Processes calling CreateFileMapping for an existing object receive a handle to the existing object. You can tell whether or not a successful call to CreateFileMapping created or opened the file mapping object by calling the GetLastError function. GetLastError returns NO_ERROR to the creating process and ERROR_ALREADY_EXISTS to subsequent processes."

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. D T 20 Reputation points
    2023-05-26T10:16:25.8766667+00:00

    It turns out that I forgot to convert the rust string into c-style string, so the filename is not ended with \0 and has extra chars.


  2. D T 20 Reputation points
    2023-05-26T10:56:20.9333333+00:00

    To convert rust string into c-style string:

    let name = CString::new(name).unwrap();
    let pointer = name.as_ptr();
    

    Fixed in:

    DiscreteTom/rusty-duplication@dc3634c
    DiscreteTom/rusty-duplication@5fd799f

    Thanks for all the responses!

    0 comments No comments