memfd_create(2)

๐ŸŒธ memfd_create(2) โ€” System Calls Manual ๐ŸŒธ

okay bestie, sit down, hydrate, and let me tell you about memfd_create from the System Calls Manual, because this one is genuinely iconic and you're gonna be obsessed. ๐Ÿ’…


โœจ NAME โœจ

memfd_create โ€” create an anonymous file ๐ŸŽ€

๐Ÿ“š LIBRARY ๐Ÿ“š

Standard C library (libc, -lc) โ€” yeah, the usual one, she's always there for you ๐Ÿ’œ

๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <sys/mman.h>

int memfd_create(const char *name, unsigned int flags);

not me putting _GNU_SOURCE at the top like a little ritual before every incantation ๐Ÿ˜ญ it literally is tho, bestie โ€” see feature_test_macros(7) if you wanna know why.


๐Ÿ’– DESCRIPTION ๐Ÿ’–

okay so. memfd_create() creates an anonymous file and hands you a file descriptor that points at it. that's it, that's the whole vibe.

the file lowkey behaves like a regular file โ€” you can modify it, truncate it, memory-map it, all of that, no cap. BUT (and this is the iconic part) unlike a regular file, it lives in RAM and has volatile backing storage. once every single reference to the file gets dropped, it just... auto-releases itself. gone. poof. she doesn't linger. ๐Ÿฆ‹โœจ

anonymous memory is used for all the backing pages of the file. so fr fr, files made by memfd_create() have the exact same semantics as other anonymous memory allocations โ€” like the ones you'd get from mmap(2) with the MAP_ANONYMOUS flag.

the initial size of the file is set to 0. bestie, she starts at zero, she's humble. after the call, you should set the file size with ftruncate(2). (or alternatively, the file can be populated by calls to write(2) or similar โ€” whatever slays for you ๐Ÿ’…)

the name you pass in is used as a filename, and it'll show up as the target of the corresponding symlink in the directory /proc/self/fd/. the displayed name is always prefixed with memfd: and it is only for debugging purposes. names do not affect the behavior of the file descriptor at all, which means multiple files can have the same name with zero side effects. no drama, no consequences, we love that for them. ๐Ÿ’–

the following values may be bitwise ORed in flags to change the behavior of memfd_create():

  • MFD_CLOEXEC โ€” sets the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. if you wanna know why that's useful, go read about the O_CLOEXEC flag in open(2), bestie, it's a whole thing. ๐Ÿ”ฅ
  • MFD_ALLOW_SEALING โ€” allows sealing operations on this file. check out the discussion of the F_ADD_SEALS and F_GET_SEALS operations in fcntl(2), and also the NOTES section below. the initial set of seals is empty. if this flag is not set, the initial set of seals will be F_SEAL_SEAL, meaning no other seals can be set on the file. like, door's locked, nobody's coming in. ๐Ÿšช๐Ÿ”’
  • MFD_HUGETLB (since Linux 4.14) โ€” the anonymous file will be created in the hugetlbfs filesystem using huge pages. for more info about hugetlbfs, see the Linux kernel source file Documentation/admin-guide/mm/hugetlbpage.rst. specifying both MFD_HUGETLB and MFD_ALLOW_SEALING in flags is supported since Linux 4.16. ๐Ÿ˜ (big pages. huge even. it's giving enormous.)
  • MFD_HUGE_2MB, MFD_HUGE_1GB, ... โ€” used in conjunction with MFD_HUGETLB to select alternative hugetlb page sizes (respectively, 2 MB, 1 GB, ...) on systems that support multiple hugetlb page sizes. definitions for known huge page sizes are included in the header file <linux/memfd.h>.

for details on encoding huge page sizes not included in the header file, see the discussion of the similarly named constants in mmap(2). iykyk ๐Ÿงš

heads up bestie: unused bits in flags must be 0. zero. not "eh, probably fine." zero.

as its return value, memfd_create() returns a new file descriptor that can be used to refer to the file. this file descriptor is opened for both reading and writing (O_RDWR) and O_LARGEFILE is set for the file descriptor. she's ready for anything, she's flexible like that. ๐Ÿ‘‘

with respect to fork(2) and execve(2), the usual semantics apply for the file descriptor created by memfd_create(). a copy of the file descriptor is inherited by the child produced by fork(2) and refers to the same file. the file descriptor is preserved across execve(2), unless the close-on-exec flag has been set. slay, but responsibly. ๐Ÿ’…


๐ŸŽ€ RETURN VALUE ๐ŸŽ€

on success, memfd_create() returns a new file descriptor. ๐Ÿฅณ

on error, -1 is returned and errno is set to indicate the error. ๐Ÿ˜ญ (we hate to see it but we respect the honesty)


๐Ÿ’€ ERRORS ๐Ÿ’€

  • EFAULT โ€” the address in name points to invalid memory. bestie that pointer is not okay.
  • EINVAL โ€” flags included unknown bits. you made bits up. don't do that.
  • EINVAL โ€” name was too long. (the limit is 249 bytes, excluding the terminating null byte.) okay she's got a limit, respect it ๐Ÿซถ
  • EINVAL โ€” both MFD_HUGETLB and MFD_ALLOW_SEALING were specified in flags. pick a lane, babe.
  • EMFILE โ€” the per-process limit on the number of open file descriptors has been reached. you have too many fds open. it's giving hoarder. ๐Ÿ˜ญ
  • ENFILE โ€” the system-wide limit on the total number of open files has been reached. the entire system is tapped out. wild.
  • ENOMEM โ€” there was insufficient memory to create a new anonymous file. no RAM, no file, that's the math. ๐Ÿ’€
  • EPERM โ€” the MFD_HUGETLB flag was specified, but the caller was not privileged (did not have the CAP_IPC_LOCK capability) and is not a member of the hugetlb_shm_group group. see the description of /proc/sys/vm/hugetlb_shm_group in proc_sys_vm(5). ๐Ÿ”’ no permission, no huge pages, no exceptions.

โญ STANDARDS โญ

Linux. (obvi ๐Ÿ’…)


๐Ÿ•ฐ๏ธ HISTORY ๐Ÿ•ฐ๏ธ

Linux 3.17, glibc 2.27.


๐Ÿ‘‘ NOTES ๐Ÿ‘‘

the memfd_create() system call provides a simple alternative to manually mounting a tmpfs(5) filesystem and creating and opening a file in that filesystem. like, why do all that when you could just... call one function? the primary purpose of memfd_create() is to create files and associated file descriptors that are used with the file-sealing APIs provided by fcntl(2). โœจ

the memfd_create() system call also has uses without file sealing (which is exactly why file-sealing is disabled unless you explicitly ask for it with the MFD_ALLOW_SEALING flag). in particular, it can be used as an alternative to creating files in tmp, or as an alternative to using the open(2) O_TMPFILE in cases where there is no intention to actually link the resulting file into the filesystem. no link, no problem, we keep it casual. ๐Ÿฆ‹

๐Ÿงš File sealing ๐Ÿงš

in the absence of file sealing, processes that communicate via shared memory must either trust each other, or take measures to deal with the possibility that an untrusted peer may manipulate the shared memory region in problematic ways. ๐Ÿ˜ฌ

for example, an untrusted peer might modify the contents of the shared memory at any time, or shrink the shared memory region.

  • the first possibility leaves the local process vulnerable to time-of-check-to-time-of-use race conditions (typically dealt with by copying data from the shared memory region before checking and using it).
  • the latter possibility leaves the local process vulnerable to SIGBUS signals when an attempt is made to access a now-nonexistent location in the shared memory region. (dealing with this possibility necessitates the use of a handler for the SIGBUS signal.)

dealing with untrusted peers imposes extra complexity on code that employs shared memory. memory sealing enables that extra complexity to be eliminated, by allowing a process to operate secure in the knowledge that its peer can't modify the shared memory in an undesired fashion. it's giving peace of mind. it's giving trust issues resolved. ๐Ÿซถโœจ

an example of the usage of the sealing mechanism is as follows:

  1. the first process creates a tmpfs(5) file using memfd_create(). the call yields a file descriptor used in subsequent steps.
  2. the first process sizes the file created in the previous step using ftruncate(2), maps it using mmap(2), and populates the shared memory with the desired data.
  3. the first process uses the fcntl(2) F_ADD_SEALS operation to place one or more seals on the file, in order to restrict further modifications on the file. (if placing the seal F_SEAL_WRITE, then it will be necessary to first unmap the shared writable mapping created in the previous step. otherwise, behavior similar to F_SEAL_WRITE can be achieved by using F_SEAL_FUTURE_WRITE, which will prevent future writes via mmap(2) and write(2) from succeeding while keeping existing shared writable mappings). ๐Ÿ”ฅ
  4. a second process obtains a file descriptor for the tmpfs(5) file and maps it. among the possible ways in which this could happen are the following:
    • the process that called memfd_create() could transfer the resulting file descriptor to the second process via a UNIX domain socket (see unix(7) and cmsg(3)). the second process then maps the file using mmap(2).
    • the second process is created via fork(2) and thus automatically inherits the file descriptor and mapping. (note that in this case and the next, there is a natural trust relationship between the two processes, since they are running under the same user ID. therefore, file sealing would not normally be necessary.) ๐Ÿ’•
    • the second process opens the file /proc/pid/fd/fd, where <pid> is the PID of the first process (the one that called memfd_create()), and <fd> is the number of the file descriptor returned by the call to memfd_create() in that process. the second process then maps the file using mmap(2).
  5. the second process uses the fcntl(2) F_GET_SEALS operation to retrieve the bit mask of seals that has been applied to the file. this bit mask can be inspected in order to determine what kinds of restrictions have been placed on file modifications. if desired, the second process can apply further seals to impose additional restrictions (so long as the F_SEAL_SEAL seal has not yet been applied). ๐Ÿ’…

okay bestie, we're not done yet โ€” there's literally more coming and you're gonna wanna stay for it ๐Ÿ‘€๐Ÿฆ‹

โœจ EXAMPLES โœจ

okay bestie, this is the part where it all clicks ๐Ÿ’ก because we're running two lil demo programs that show off memfd_create() and the file sealing API in action. no cap, it's giving "show don't tell" and we are obsessed. ๐Ÿซถ

So the first program, t_memfd_create.c, creates a tmpfs(5) file using memfd_create(), sets a size for the file, maps it into memory, and โ€” if you want โ€” optionally places some seals on the file. She takes up to three command-line arguments, and heads up, the first two are required (not optional, not vibes, required ๐Ÿ’…):

  • the first argument is the name to associate with the file
  • the second argument is the size to be set for the file
  • the optional third argument is a string of characters that specify seals to be set on the file

And the second program, t_get_seals.c, is the nosy bestie of the duo ๐Ÿ•ต๏ธ โ€” you use it to open an existing file that was created via memfd_create() and inspect the set of seals that have been applied to that file.


Now here's a shell session demonstrating both programs. First we create a tmpfs(5) file and set some seals on it:

$ ./t_memfd_create my_memfd_file 4096 sw &
[1] 11775
PID: 11775; fd: 3; /proc/11775/fd/3

At this point, the t_memfd_create program continues to run in the background โ€” she's not leaving, she's just being mysterious. ๐Ÿ˜Œ From another program, we can obtain a file descriptor for the file created by memfd_create() by opening the /proc/pid/fd file that corresponds to the file descriptor opened by memfd_create(). Using that pathname, we inspect the content of the /proc/pid/fd symbolic link, and use our t_get_seals program to view the seals that have been placed on the file:

$ readlink /proc/11775/fd/3;
/memfd:my_memfd_file (deleted)
$ ./t_get_seals /proc/11775/fd/3;
Existing seals: WRITE SHRINK

iconic. โœจ the seals are WRITE and SHRINK and the file is literally named after itself in the link. main character energy fr fr.

Program source: t_memfd_create.c

#define _GNU_SOURCE
#include <err.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>

int
main(int argc, char *argv[])
{
    int           fd;
    char          *name, *seals_arg;
    ssize_t       size;
    unsigned int  seals;

    if (argc < 3) {
        fprintf(stderr, "%s name size [seals]\n", argv[0]);
        fprintf(stderr, "\t'seals' can contain any of the "
                "following characters:\n");
        fprintf(stderr, "\t\tg - F_SEAL_GROW\n");
        fprintf(stderr, "\t\ts - F_SEAL_SHRINK\n");
        fprintf(stderr, "\t\tw - F_SEAL_WRITE\n");
        fprintf(stderr, "\t\tW - F_SEAL_FUTURE_WRITE\n");
        fprintf(stderr, "\t\tS - F_SEAL_SEAL\n");
        exit(EXIT_FAILURE);
    }

    name = argv[1];
    size = atoi(argv[2]);
    seals_arg = argv[3];

    /* Create an anonymous file in tmpfs; allow seals to be
       placed on the file.  */

    fd = memfd_create(name, MFD_ALLOW_SEALING);
    if (fd == -1)
        err(EXIT_FAILURE, "memfd_create");

    /* Size the file as specified on the command line.  */

    if (ftruncate(fd, size) == -1)
        err(EXIT_FAILURE, "truncate");

    printf("PID: %jd; fd: %d; /proc/%jd/fd/%d\n",
           (intmax_t) getpid(), fd, (intmax_t) getpid(), fd);

    /* Code to map the file and populate the mapping with data
       omitted.  */

    /* If a 'seals' command-line argument was supplied, set some
       seals on the file.  */

    if (seals_arg != NULL) {
        seals = 0;

        if (strchr(seals_arg, 'g') != NULL)
            seals |= F_SEAL_GROW;
        if (strchr(seals_arg, 's') != NULL)
            seals |= F_SEAL_SHRINK;
        if (strchr(seals_arg, 'w') != NULL)
            seals |= F_SEAL_WRITE;
        if (strchr(seals_arg, 'W') != NULL)
            seals |= F_SEAL_FUTURE_WRITE;
        if (strchr(seals_arg, 'S') != NULL)
            seals |= F_SEAL_SEAL;

        if (fcntl(fd, F_ADD_SEALS, seals) == -1)
            err(EXIT_FAILURE, "fcntl");
    }

    /* Keep running, so that the file created by memfd_create()
       continues to exist.  */

    pause();

    exit(EXIT_SUCCESS);
}

Program source: t_get_seals.c

#define _GNU_SOURCE
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    int           fd;
    unsigned int  seals;

    if (argc != 2) {
        fprintf(stderr, "%s /proc/PID/fd/FD\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    fd = open(argv[1], O_RDWR);
    if (fd == -1)
        err(EXIT_FAILURE, "open");

    seals = fcntl(fd, F_GET_SEALS);
    if (seals == -1)
        err(EXIT_FAILURE, "fcntl");

    printf("Existing seals:");
    if (seals & F_SEAL_SEAL)
        printf(" SEAL");
    if (seals & F_SEAL_GROW)
        printf(" GROW");
    if (seals & F_SEAL_WRITE)
        printf(" WRITE");
    if (seals & F_SEAL_FUTURE_WRITE)
        printf(" FUTURE_WRITE");
    if (seals & F_SEAL_SHRINK)
        printf(" SHRINK");
    printf("\n");

    /* Code to map the file and access the contents of the
       resulting mapping omitted.  */

    exit(EXIT_SUCCESS);
}

๐ŸŒˆ SEE ALSO ๐ŸŒˆ

go be a little explorer bestie, these are the friends in the same friend group ๐Ÿ’–:


and that's the whole page, babe ๐ŸŽ€ this one came from the Linux man-pages 6.20 era, dated 2026-02-08, and it's the memfd_create(2) page. go forth and seal things (only the files you're supposed to seal tho ๐Ÿ”ฅ). slay, periodt. ๐Ÿ’…โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: GPL-2.0-or-later
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms