Fix shared file: open and close the file inside the critical region