#include #include #include #include #include #define HAVE_POSIX_FALLOCATE 1 int os_resize_anonymous_file(int fd, off_t size) { #ifdef HAVE_POSIX_FALLOCATE /* * Filesystems that do support fallocate will return EINVAL or * EOPNOTSUPP. In this case we need to fall back to ftruncate */ errno = posix_fallocate(fd, 0, size); if (errno == 0) return 0; else if (errno != EINVAL && errno != EOPNOTSUPP) { warn("posix_fallocate failed"); return -1; } #endif if (ftruncate(fd, size) < 0) { warn("ftruncate failed"); return -1; } return 0; } int main(void) { int fd; off_t size = 12345; fd = shm_open(SHM_ANON, O_CREAT | O_RDWR | O_CLOEXEC, 0600); // shm_open is always CLOEXEC if (fd < 0) err(1, "shm_open(SHM_ANON) failed"); if (os_resize_anonymous_file(fd, size) < 0) { close(fd); return -1; } return 0; }