What are the reasons to check for error on close()?

前端 未结 2 904
日久生厌
日久生厌 2020-12-09 04:50

Note: Please read to the end before marking this as duplicate. While it\'s similar, the scope of what I\'m looking for in an answer extends beyond what the

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 05:08

    Consider the inverse of your question: "Under what situations can we guarantee that close will succeed?" The answer is:

    • when you call it correctly, and
    • when you know that the file system the file is on does not return errors from close in this OS and Kernel version

    If you are convinced that you program doesn't have any logic errors and you have complete control over the Kernel and file system, then you don't need to check the return value of close.

    Otherwise, you have to ask yourself how much you care about diagnosing problems with close. I think there is value in checking and logging the error for diagnostic purposes:

    • If a coder makes a logic error and passes an invalid fd to close, then you'll be able to quickly track it down. This may help to catch a bug early before it causes problems.
    • If a user runs the program in an environment where close does return an error when (for example) data was not flushed, then you'll be able to quickly diagnose why the data got corrupted. It's an easy red flag because you know the error should not occur.

提交回复
热议问题