fix unsynchronized access to FILE structure in fflush(0)
[musl.git] / src / stdio / fflush.c
blobbf1e843765761a4566ccb15130c94a0cc449a2c5
1 #include "stdio_impl.h"
3 /* stdout.c will override this if linked */
4 static FILE *volatile dummy = 0;
5 weak_alias(dummy, __stdout_used);
7 int fflush(FILE *f)
9 if (!f) {
10 int r = __stdout_used ? fflush(__stdout_used) : 0;
12 for (f=*__ofl_lock(); f; f=f->next) {
13 FLOCK(f);
14 if (f->wpos > f->wbase) r |= fflush(f);
15 FUNLOCK(f);
17 __ofl_unlock();
19 return r;
22 FLOCK(f);
24 /* If writing, flush output */
25 if (f->wpos > f->wbase) {
26 f->write(f, 0, 0);
27 if (!f->wpos) {
28 FUNLOCK(f);
29 return EOF;
33 /* If reading, sync position, per POSIX */
34 if (f->rpos < f->rend) f->seek(f, f->rpos-f->rend, SEEK_CUR);
36 /* Clear read and write modes */
37 f->wpos = f->wbase = f->wend = 0;
38 f->rpos = f->rend = 0;
40 FUNLOCK(f);
41 return 0;
44 weak_alias(fflush, fflush_unlocked);