POSIX/UNIX: How to reliably close a file descriptor

前端 未结 3 1353
清酒与你
清酒与你 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:16

    To mitigate any issues, explicitly sync the file:

    1. (If you are operating on FILE*, first call fflush() on it to make sure user space buffers are emptied to kernel.)
    2. Call fsync() on the file descriptor, to flush any kernel data and metadata about the file to disk.

    These you can retry on error without extra worries. After that, possibly leaking file descriptors or handles on interrupted close on some OSes is probably a minor issue, especially if you check the behavior for OSes which are important to you (I suspect there's no problem in most relevant OSes).

    Also, once the file and data are flushed, the chances of getting interrupted during close is much smaller, as then close should not actually touch disk. If you do get EIO or EINTR anyway, just (optionally) log it and ignore it, because doing anything else probably does more harm than good. It's not a perfect world.

提交回复
热议问题