Search code examples
pythonwindowsmemory-mapped-fileswindows-server-2019local-security-policy

Python mmap permission denied on Windows


I have the following code that works perfectly:

server.py

from mmap import mmap
from pickle import load, dump


mm = mmap(-1, 32, tagname='test')

last_request_id = None
while True:
    mm.seek(0)
    try:
        request_id = int(load(mm))
        if request_id != last_request_id:
            last_request_id = request_id
            print(request_id)
        
    except Exception:
        pass

client.py

from mmap import mmap
from pickle import dump


with mmap(-1, 32, tagname='test') as mm:
    request_id = 1
    dump(request_id, mm)

So every time the server receives a new request id, the server prints the id on the console. But now I want to use the global scope. So I changed the tagname on both (client and server) to r'Global\test'. With that change, when the servers or the client starts it shows a permission error:

PermissionError: [WinError 5] Access is denied

So I read this awnswer that it is a security mechanism that prevents anyone to create a global memory mapped file and that administrators, IIS users, or services, by default have permission to create a global memory mapped file. Knowing that I created a Windows service that runs the server and it does not give any errors, the server was able to create the global mmap. But the problem persists on the client side (permission error).

Reading the Microsoft docs, it says "the privilege check is limited to the creation of file-mapping objects"... " any process running in any session can access that file-mapping object provided that the user has the necessary access". I want to known what I have to do to read the global mmap created by the server on my client application.


Solution

  • You need to call the OpenFileMapping() at the client. But currently the Python mmap module calls the CreateFileMapping() to open an existing file mapping object.(You can see that at this.)

    So you can't do what you want in pure Python. I recommend using other IPC mechanisms provided by multiprocessing module.(The multiprocessing.shared_memory.SharedMemory will not help because it calls the mmap API in the backend.)

    As a side note, I recommend you to make an issue report on here.