Skip to content

Os File Mmap Io

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix Memory. We cover key concepts, practical examples, and best practices.

Fix memory-mapped i/o errors when mmap file size changes after mapping causing SIGBUS on access.

Quick Fix

Wrong

import mmap, os
with open('file.bin','r+b') as f:
    mm=mmap.mmap(f.fileno(), 0)
    os.ftruncate(f.fileno(), 10)  # truncate after mapping!
    print(mm[10])  # SIGBUS - file shorter than mapped region!

Truncating file after mmap causes access beyond file size. SIGBUS crash.

import mmap, os
with open('file.bin','wb+') as f:
    f.write(b'x'*100)  # ensure file size first
    f.flush()
    mm=mmap.mmap(f.fileno(), 0)
    mm[50]=ord('y')
    mm.close()
# If file must be resized, remap:
with open('file.bin','rb+') as f:
    mm=mmap.mmap(f.fileno(), 0)
    print(f'Size: {len(mm)}')
    # To extend: munmap, ftruncate, mmap again
    size=len(mm)
    mm.close()
    f.truncate(size+100)
    mm2=mmap.mmap(f.fileno(), 0)
    print(f'New size: {len(mm2)}')
File size fixed before mmap. Remap after resize. No SIGBUS.

Prevention

Don't change file size while mmap'd. If resize needed, munmap, truncate, remap.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is SIGBUS?

Accessing memory beyond underlying file/device. Signal indicating mapping no longer valid.

mmap resizing?

fd.ftruncate() after mmap creates mismatch. Must unmap, truncate, remap.

Length 0?

mmap(..., 0) maps entire file from current size.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro