Fix #4923 - close process race when truncating existing file
Using File.open(file, "w") calls open(2) with O_CREAT|O_TRUNC which
means when the file exists it is immediately truncated.
But the file is not locked yet, so another process can either write or
read to the file, leading to file corruption.
The fix is to truncate only when the file is exclusively locked. This can
be done on some operating system with O_EXLOCK open(2) flag.
I chose the more portable option of:
- open
- flock
- truncate
- write
- close
It might also be good to flush and fsync the file after writing it,
otherwise in case of crash an incomplete file can stay on disk.
Signed-off-by: Brice Figureau <brice-puppet@daysofwonder.com>