chiark / gitweb /
@@ -3,7 +3,10 @@
[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 #include <string.h>
34
35 #include "config.h"
36 #include "both.h"
37
38 void *xmalloc(size_t s) {
39   void *p;
40   p= malloc(s?s:1); if (!p) syscallerror("malloc");
41   return p;
42 }
43
44 void *xrealloc(void *p, size_t s) {
45   p= realloc(p,s);
46   if (!p) syscallerror("realloc");
47   return p;
48 }
49
50 char *xstrsave(const char *s) {
51   char *r;
52
53   r= xmalloc(strlen(s)+1);
54   strcpy(r,s);
55   return r;
56 }
57
58
59 int working_getc(FILE *file) {
60   int c;
61   
62   for (;;) {
63     c= getc(file);
64     if (c != EOF || errno != EINTR) return c;
65     clearerr(file);
66   }
67 }
68
69 size_t working_fread(void *ptr, size_t sz, FILE *file) {
70   size_t done, nr;
71
72   done= 0;
73   for (;;) {
74     nr= fread((char*)ptr + done, 1, sz-done, file);
75     done += nr;
76     if (done == sz || !ferror(file) || errno != EINTR) return done;
77     clearerr(file);
78   }
79 }