OpenFileMapping got error code 2 unpredictably

D T 20 Reputation points

I'm creating named shared memory following

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


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

Process B:

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,069 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 32,146 Reputation points

    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

    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

    To convert rust string into c-style string:

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

    Fixed in:


    Thanks for all the responses!

    0 comments No comments