Python mmap 'Permission denied' on Linux

喜你入骨 提交于 2019-12-05 00:18:24
Bobby Powers

I think its a flags issue, try opening as read only:

mfd = os.open('BigFile', os.O_RDONLY)

and mmap.mmap by default tries to map read/write, so just map read only:

mfile = mmap.mmap(mfd, 0, prot=mmap.PROT_READ)

Try setting the file mode to r+. That worked for me on Linux:

mfd = os.open('BigFile', "r+")

Then this worked for me as normal:

mfile = mmap.mmap(mfd, 0)

In my case this error occurred because I was attempting to open a block device without specifying an explicit size.

FWIW you cannot use os.stat / os.fstat with a block device to obtain the device's size (which is always 0), but you can use file.seek and file.tell:

f = file("/dev/loop0", "rb")
f.seek(0, 2)  # Seek relative to end of file
size = f.tell()
fh = f.fileno()

m = mmap.mmap(f, size, mmap.MAP_PRIVATE, mmap.PROT_READ)

The cross-platform call of mmap can be performed using access parameter:

mfd = os.open('BigFile', os.O_RDONLY)
mm = mmap.mmap(mfd, 0, access=mmap.ACCESS_READ)

The mmap construction permissions should be synced with the file open permissions (both read, write, or read/write).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!