Add file lock to write one xml file at a time

Use flock for file lock and add file close operation to fix previous bug.