#include #include #include #include #include #include bool is_directory(const char *path) { struct stat st; if (stat(path, &st) == -1) { printf("Error: %s\n", strerror(errno)); return false; } return S_ISDIR(st.st_mode); } bool append(int fd, size_t size) { void* buffer = malloc(size); memset(buffer, 0, size); if (write(fd, buffer, size) <= 0) { printf("Error in append: %s\n", strerror(errno)); free(buffer); return 0; } free(buffer); return 1; } int fd_open_file_for_create(const char *path) { int fd = open(path, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); if (fd < 0) { printf("Error in file opening: %s\n", strerror(errno)); return 1; } return fd; } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } const char *directory = argv[1]; if (!is_directory(directory)) { printf("Error: %s is not a directory\n", directory); return 1; } const std::string mapped_file_path = std::string(directory) + "/map.data"; size_t mmap_size = 1024 * 1024 * 100; // create a large file filled with 0 { int fd = fd_open_file_for_create(mapped_file_path.c_str()); for (int i = 0; i < (mmap_size / 1024); i++) { if (!append(fd, 1024)) { break; } } close(fd); } // mmap that file int mapped_fd = open(mapped_file_path.c_str(), O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); if (mapped_fd < 0) { printf("Error in file opening: %s\n", strerror(errno)); return 1; } // we get the same behavior if we fallocate the mapped file, instead of filling it with zeros. // if (fallocate(mapped_fd, 0, 0, mmap_size) < 0) { // printf("Error in file allocation: %s\n", strerror(errno)); // return 1; //} char* ptr = (char*)mmap(nullptr, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, mapped_fd, 0); // open another file, and write into it until the disk is full const std::string data_file_path = std::string(directory) + "/file.data"; // create a large file filled with 0 { int fd = fd_open_file_for_create(data_file_path.c_str()); for (int i = 0; i < (mmap_size / 1024); i++) { if (!append(fd, 1024)) { break; } } close(fd); } // now, try to write into the mapped file. With btrfs, it crashes. With ext4, it does not ptr[0] = 0; close(mapped_fd); }