c - 如果fclose()失败,文件描述符是否仍然打开?

标签 c posix fclose

想象下面的代码作为线程运行:

void *thread_worker(void *q) {
 for (;;) {
  int fd = some_queue_get(q);
  FILE *writer = fdopen(fd, "w");
  if (!writer) { perror("fdopen"; close(fd); continue; }
  // do something with writer

  if (fclose(writer) == EOF) {
   perror("fclose writer");
   // should fd be closed here?
   close(fd);
  }
}
fclose(3)可能由于各种原因而失败-是否可以保证/当底层文件描述符关闭时或之后仍然打开?
  • 如果在刷新失败时未通过fclose关闭fd,则会泄漏fds而不会进行其他关闭。
  • 如果fd由fclose关闭,则额外的关闭可能会关闭由另一个线程新打开的文件描述符。
  • 最佳答案

    man fclose也不提供我系统上的答案,但是man 3p fclose揭示了official version from the POSIX Programmer's manual,它在此问题上更加全面:

    The fclose() function shall perform the equivalent of a close() on the file descriptor that is associated with the stream pointed to by stream.

    关于c - 如果fclose()失败,文件描述符是否仍然打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66048264/

    相关文章:

    C - fclose() 触发断点

    c++ - 使用 fclose() 关闭文件但文件仍在使用中

    c - 如何将 char 数组表示为 c 中的单个字符串

    c - 将数组类型转换为 C 中的结构

    c - pthreads - 加入一组线程,等待一个线程退出

    c - 具有 FIFO 的 Posix 信号量无法正常工作

    c++ - opencv c和c++接口(interface)转换表

    c++ - 是否有可能在多次乘法**溢出**后得到一个数字的原始值?

    c - 障碍,获取和获取线

    c++ - Valgrind 在 fclose() 处检测到内存泄漏