I am trying to create a memory mapped file like this

size = 83456
self.file = open("/tmp/installer.ipk", "r+b")
self.mm = mmap.mmap(self.file.fileno(), size, access=mmap.ACCESS_WRITE)

but I get the following exception

Traceback (most recent call last):
   ...
  File "./dept_sensor_service.py", line 70, in handle_control
    self.mm = mmap.mmap(self.file.fileno(), size, access=mmap.ACCESS_WRITE)
ValueError: mmap length is greater than file size

The file /tmp/installer.ipk does not exist before I run this. I want the script to create a file called /tmp/installer.ipk and filled with 83456 zeros. According to the python documentation for mmap:

If length is larger than the current size of the file, the file is extended to contain length bytes

I've played around with various permissions, but I would think that 'r+b' for the file and ACCESS_WRITE for the map would be correct.

This is on a beaglebone Linux box. BTW, I would have used the with open(...) as f: pattern, but I can't in this case as the mmap has to remain open after the function returns.

有帮助吗?

解决方案

The unix version of mmap doesn't grow the file automatically, but you can just write zeros to the file yourself, something like:

size = 83456
self.file = open("/tmp/installer.ipk", "w+b")
self.file.write("\0" * size)
self.file.flush()
self.mm = mmap.mmap(self.file.fileno(), size, access=mmap.ACCESS_WRITE)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top