thejonny
thejonny

Reputation: 533

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

Imagine the following code running as a thread:

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) can fail for various reasons - is there a guarantee that/when the underlying file descriptor is closed or that it is still open afterwards?

Upvotes: 10

Views: 915

Answers (2)

chqrlie
chqrlie

Reputation: 144740

The answer is NO, the C Standard is ambiguous about this (emphasis mine):

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.

Upvotes: 0

Thomas
Thomas

Reputation: 181745

man fclose does not provide the answer on my system either, but man 3p fclose reveals the official version from the POSIX Programmer's manual, which is much more comprehensive on the matter:

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

Upvotes: 2

Related Questions