fix usage of locks with vfork
[musl] / src / stdio / fgets.c
1 #include "stdio_impl.h"
2
3 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4
5 char *fgets(char *restrict s, int n, FILE *restrict f)
6 {
7         char *p = s;
8         unsigned char *z;
9         size_t k;
10         int c;
11
12         if (n--<=1) {
13                 if (n) return 0;
14                 *s = 0;
15                 return s;
16         }
17
18         FLOCK(f);
19
20         while (n) {
21                 z = memchr(f->rpos, '\n', f->rend - f->rpos);
22                 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
23                 k = MIN(k, n);
24                 memcpy(p, f->rpos, k);
25                 f->rpos += k;
26                 p += k;
27                 n -= k;
28                 if (z || !n) break;
29                 if ((c = getc_unlocked(f)) < 0) {
30                         if (p==s || !feof(f)) s = 0;
31                         break;
32                 }
33                 n--;
34                 if ((*p++ = c) == '\n') break;
35         }
36         *p = 0;
37
38         FUNLOCK(f);
39
40         return s;
41 }
42
43 weak_alias(fgets, fgets_unlocked);