chiark / gitweb /
finalise
[userv.git] / both.c
1 /*
2  * userv - both.c
3  * Useful very-low-level utility routines, used in both client and daemon.
4  * These do not (and cannot) depend on infrastructure eg syscallerror,
5  * because these are not the same.
6  *
7  * Copyright (C)1999 Ian Jackson
8  *
9  * This is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with userv; if not, write to the Free Software
21  * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22  */
23
24 /* Some nasty people can return 0/EOF + EINTR from stdio !
25  * These functions attempt to work around this braindamage by retrying
26  * the call after clearerr.  If this doesn't work then clearly your
27  * libc is _completely_ fubar rather than just somewhat fubar.
28  */
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <errno.h>
33
34 #include "config.h"
35 #include "both.h"
36
37 void *xmalloc(size_t s) {
38   void *p;
39   p= malloc(s?s:1); if (!p) syscallerror("malloc");
40   return p;
41 }
42
43 void *xrealloc(void *p, size_t s) {
44   p= realloc(p,s);
45   if (!p) syscallerror("realloc");
46   return p;
47 }
48
49 char *xstrsave(const char *s) {
50   char *r;
51
52   r= xmalloc(strlen(s)+1);
53   strcpy(r,s);
54   return r;
55 }
56
57
58 int working_getc(FILE *file) {
59   int c;
60   
61   for (;;) {
62     c= getc(file);
63     if (c != EOF || errno != EINTR) return c;
64     clearerr(file);
65   }
66 }
67
68 size_t working_fread(void *ptr, size_t sz, FILE *file) {
69   size_t done, nr;
70
71   done= 0;
72   for (;;) {
73     nr= fread((char*)ptr + done, 1, sz-done, file);
74     done += nr;
75     if (done == sz || !ferror(file) || errno != EINTR) return done;
76     clearerr(file);
77   }
78 }