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

If fclose() fails, is the file descriptor still open?

将以下代码 运行 想象成一个线程:

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) 可能因各种原因而失败 - 是否可以保证 that/when 底层文件描述符已关闭或之后仍处于打开状态?

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标准对此不明确(强调我的):

7.21.5.1 The fclose function

Synopsis

#include <stdio.h>
int fclose(FILE *stream);
 

Description
A successful call to the fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream (and deallocated if it was automatically allocated).

Returns
The fclose function returns zero if the stream was successfully closed, or EOF if any errors were detected.