Search code examples
clinuxposixfallocate

How does linux fallocate FALLOC_FL_KEEP_SIZE affect a file after it is closed?


The linux call

fallocate(fd, FALLOC_FL_KEEP_SIZE, offset, len);

can be used to preallocate space for the file after the end of the file without increasing the length of the file. (right?)

Question: what happens to this disk space when fd is closed? Is the extra space released, or does it remain associated with the file?

If it remains associated with the file, how do I free that space? Does truncate (or open() and ftruncate()) free the space?


Solution

  • Question: what happens to this disk space when fd is closed? Is the extra space released, or does it remain associated with the file?

    Nothing happens. The allocated space is independent of the fd.

    If it remains associated with the file, how do I free that space? Does truncate (or open() and ftruncate()) free the space?

    truncate() is the main way to reclaim the space. Another way is deleting the file. You could also try calling fallocate() with FALLOC_FL_PUNCH_HOLE and FALLOC_FL_KEEP_SIZE on the "overallocated" parts of the file, though that seems messy and may leave artifacts.

    Under the hood, extending a file with FALLOC_FL_KEEP_SIZE will allocate the blocks in the filesystem but leave them marked as uninitialized. Not all filesystems support this. So far this is the same as a calling fallocate() without the keep size flag. The difference with the keep size flag is that it will leave the size field in the inode (which is independent of the block allocation) untouched. All this happens on disk; in the shell you can use

    ls -s
    

    or

    stat
    

    to observe the true allocated block count independently of whichever process/fd was used to made the fallocate() call.