mmap_shared(3)

πŸ“¦
version 0.34 Β· 3 versions
, in alpine 3.24, nixos 26.05, nixpkgs unstable, opensuse-leap 16.0, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

okay bestie, gather round β€” mmap_shared is the one that memory maps a file for reading and writing. that's it, that's the whole vibe. it's from the libowfat crew, sitting pretty in section 3 (Library Functions Manual) ✨


πŸŽ€ SYNTAX πŸŽ€

like, this is literally what you type to summon her:

#include <libowfat/mmap.h>

char* mmap_shared(const char* filename,size_t* filesize);

no cap, that's the whole signature πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

okay so here's the tea β˜• β€” mmap_shared does a whole little routine and it's honestly iconic:

  1. opens filename for reading and writing
  2. maps the whole file into memory
  3. closes the file (yes, immediately, she's efficient like that πŸ’…)
  4. writes the length of the file into filesize
  5. returns a pointer to the mapped file 🫢

the file gets mapped shared. and bestie, that word is doing SO much work here β€” any changes you make to the mapped region get written to disk, and they're visible to other processes that are reading from the file or mapping that same file into memory. it's giving main character energy, everybody sees your edits ✨πŸ”₯

the way that the operating system unmaps the file if the process terminates?? automatic, no cleanup needed, she's self-sufficient 😌

but if you're the type who likes to be in control (respect), you can manually unmap it by calling munmap from <sys/mman.h>. iykyk 🌸

and if you're impatient and want your changes on disk, like, right now, you can use msync from <sys/mman.h>. go off, force that flush πŸ’–

now the sad part 😭 β€” if the file could not be opened or mapped, you get (void*)0 back. so please, for the love of everything, check your return value. not me watching you dereference a null pointer fr fr πŸ’€


🌈 SEE ALSO 🌈

the besties, the squad, the group chat πŸ‘‘:


okay that's the whole page, we ate and left absolutely no crumbs πŸ“βœ¨ this was mmap_shared(3) from the Library Functions Manual β€” a <rainbow>libowfat</rainbow> classic, brought to you by section 3, and she says bye bestie, go map something responsibly πŸ’œπŸ¦‹πŸŽ€