This looks like a race. Isn't there a way to open and lock a file in one shot?