/** * @file SharedMemory.cpp * @author apio (cloudapio.eu) * @brief Create and map areas of memory shared between processes. * * @copyright Copyright (c) 2023, the Luna authors. * */ #include #include #include #include #include #include #include namespace os::SharedMemory { Result create(StringView path, usize size) { int fd = shm_open(path.chars(), O_RDWR | O_CREAT | O_EXCL, 0660); if (fd < 0) { int olderr = errno; os::eprintln("os: could not create shared memory region: shm_open failed (%s) - %s", path, strerror(olderr)); return err(olderr); } size = align_up(size); if (ftruncate(fd, size) < 0) { int olderr = errno; os::eprintln("os: could not create shared memory region: ftruncate failed (%d, %zu) - %s", fd, size, strerror(olderr)); shm_unlink(path.chars()); close(fd); return err(olderr); } void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { int olderr = errno; os::eprintln("os: could not create shared memory region: mmap failed (%zu, %d) - %s", size, fd, strerror(olderr)); shm_unlink(path.chars()); close(fd); return err(olderr); } close(fd); return (u8*)p; } Result adopt(StringView path, usize size, bool delete_fs) { int fd = shm_open(path.chars(), O_RDWR, 0660); if (delete_fs) shm_unlink(path.chars()); if (fd < 0) return err(errno); void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { int olderr = errno; os::eprintln("os: could not adopt shared memory region: mmap failed (%zu, %d) - %s", size, fd, strerror(olderr)); close(fd); return 0; } close(fd); return (u8*)p; } }