2

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.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123

1 Answers1

2

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)
Bi Rico
  • 25,283
  • 3
  • 52
  • 75
  • Thanks. I reread the documentation and realized I was reading the Windows section. Here is another way to write the file to a fixed size, which supposedly is a bit faster: http://stackoverflow.com/questions/8816059/create-file-of-particular-size-in-python – Mark Lakata Jan 15 '14 at 01:20