fix race condition in IO functions

The previous code attempts to protect against race conditions by using
flock, but the open call will wipe the file before it can be locked.