preserve errno across free
[musl.git] / src / stdio / fclose.c
blobd594532bd64fdb5695544d67ee4dababd4c9a214
1 #include "stdio_impl.h"
2 #include <stdlib.h>
4 static void dummy(FILE *f) { }
5 weak_alias(dummy, __unlist_locked_file);
7 int fclose(FILE *f)
9 int r;
11 FLOCK(f);
12 r = fflush(f);
13 r |= f->close(f);
14 FUNLOCK(f);
16 /* Past this point, f is closed and any further explict access
17 * to it is undefined. However, it still exists as an entry in
18 * the open file list and possibly in the thread's locked files
19 * list, if it was closed while explicitly locked. Functions
20 * which process these lists must tolerate dead FILE objects
21 * (which necessarily have inactive buffer pointers) without
22 * producing any side effects. */
24 if (f->flags & F_PERM) return r;
26 __unlist_locked_file(f);
28 FILE **head = __ofl_lock();
29 if (f->prev) f->prev->next = f->next;
30 if (f->next) f->next->prev = f->prev;
31 if (*head == f) *head = f->next;
32 __ofl_unlock();
34 free(f->getln_buf);
35 free(f);
37 return r;