terminate properly if write fail