Fix memory and dead connection issues in file writing procceses