POSIX/UNIX: How to reliably close a file descriptor

前端 未结 3 1352
清酒与你
清酒与你 2020-12-31 09:22

Problem:

After a close() syscall that fails with EINTR or EIO it is unspecified whether the file has been closed. (http://pubs.opengroup.org/onlinepubs/9699919799

3条回答
  •  长发绾君心
    2020-12-31 10:27

    There's no practical solution for this problem as POSIX doesn't address this at all.

    Not retrying the close may result in unusable open file descriptors piling up.

    As much as it sounds like legitimate concern, I have never seen this happen due to failed close() calls.

    A clean solution might involve invoking fstat() on the freshly closed file descriptor and a quite complex locking mechanism.

    Not really. When close() failed, the state of the file descriptor is unspecified. So, you can't reliably use it a fstat() call. Because the file descriptor might have been closed already. In that case, you are passing an invalid file descriptor to fstat(). Or another thread might have reused it. In that case, you are passing the wrong file descriptor to fstat(). Or the file descriptor might have been corrupted by the failed close() call.

    When process exits, all the open descriptors will be flushed and closed anyway. So, this isn't much of a practical concern. One could argue that this would be a problem in a long running process in which close() fails too often. But I have seen this happen in my experience and POSIX doesn't provide any alternative either.

    Basically, you can't do much about this except report that the problem occurred.

提交回复
热议问题