Close fd after using it and before deleting it (closes #4075)