memfd.org
← All notes

Linux / memory

A file without a filename

A small introduction to memfd_create: file descriptors, anonymous storage, and the lifetime of an open file.

Most files begin with a name. An application opens a path, gets a file descriptor, and uses that descriptor to read or write. Linux also lets a process create a file that never needs a pathname in the first place.

Start with a descriptor

memfd_create() returns a descriptor for an anonymous file. It behaves like a regular file in many useful ways: you can write to it, resize it with ftruncate(), or map it with mmap(). Its contents live in volatile memory and can be swapped.

import os

fd = os.memfd_create("scratch", os.MFD_CLOEXEC)
try:
    os.write(fd, b"hello from memory\n")
    os.lseek(fd, 0, os.SEEK_SET)
    print(os.read(fd, 64).decode(), end="")
finally:
    os.close(fd)

A name for debugging

The string passed to memfd_create() is a label, not a filesystem path. It helps identify the descriptor under /proc/<pid>/fd/. Two anonymous files can have the same label without referring to the same contents.

Lifetime follows references

There is no temporary pathname to clean up. The anonymous file disappears once all references to it are released. That includes descriptors held by other processes and mappings that still reference the file.

For shared buffers, another useful feature is sealing: with the right creation flags, a process can restrict later changes to a file. That is a separate decision from simply keeping the file anonymous.

← Back to the notebook