0

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?

Acorn
  • 768
  • 6
  • 15
  • There is a `fallocate` command with the same name as a function (and which presumably uses the function). The command couldn't possibly leave the file open, so its effects must persist after it has closed the file. – Ian Abbott Apr 28 '21 at 09:15
  • Great point, Ian! And `man fallocate` also mentions that allocating with --keep-size "...may effectively allocate blocks past EOF, which can be removed with a truncate" which answers my other question. If you make your comment into an answer I will accept it! Thanks! – Acorn Apr 29 '21 at 16:53

1 Answers1

1

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.