chiark / gitweb /
xfoo => mfoo, add comment
[inn-innduct.git] / lib / reservedfd.c
1 /*  $Id: reservedfd.c 6135 2003-01-19 01:15:40Z rra $
2 **
3 */
4
5 #include "config.h"
6 #include "clibrary.h"
7 #include <fcntl.h>
8
9 #include "libinn.h"
10
11
12 static FILE **Reserved_fd = NULL;
13 static int Maxfd = -1;
14
15 bool
16 fdreserve(int fdnum)
17 {
18     static int allocated = 0;
19     int i, start = allocated;
20
21     if (fdnum <= 0) {
22         if (Reserved_fd != NULL) {
23             for (i = 0 ; i < Maxfd ; i++) {
24                 fclose(Reserved_fd[i]);
25             }
26             free(Reserved_fd);
27             Reserved_fd = NULL;
28         }
29         Maxfd = -1;
30         allocated = 0;
31         return true;
32     }
33     if (Reserved_fd == NULL) {
34         Reserved_fd = xmalloc(fdnum * sizeof(FILE *));
35         allocated = fdnum;
36     } else {
37         if (allocated < fdnum) {
38             Reserved_fd = xrealloc(Reserved_fd, fdnum * sizeof(FILE *));
39             allocated = fdnum;
40         } else if (Maxfd > fdnum) {
41             for (i = fdnum ; i < Maxfd ; i++) {
42                 fclose(Reserved_fd[i]);
43             }
44         }
45     }
46     for (i = start ; i < fdnum ; i++) {
47         if (((Reserved_fd[i] = fopen("/dev/null", "r")) == NULL)){
48             for (--i ; i >= 0 ; i--)
49                 fclose(Reserved_fd[i]);
50             free(Reserved_fd);
51             Reserved_fd = NULL;
52             allocated = 0;
53             Maxfd = -1;
54             return false;
55         }
56     }
57     Maxfd = fdnum;
58     return true;
59 }
60
61 FILE *
62 Fopen(const char *p, const char *type, int xindex)
63 {
64     FILE *nfp;
65     if (p == NULL || *p == '\0')
66         return NULL;
67     if (xindex < 0 || xindex > Maxfd || Reserved_fd[xindex] == NULL)
68         return fopen(p, type);
69     if ((nfp = freopen(p, type, Reserved_fd[xindex])) == NULL) {
70         Reserved_fd[xindex] = freopen("/dev/null", "r", Reserved_fd[xindex]);
71         return NULL;
72     }
73     return (Reserved_fd[xindex] = nfp);
74 }
75
76 int
77 Fclose(FILE *fp)
78 {
79     int i;
80
81     if (fp == NULL)
82         return 0;
83     for (i = 0 ; i < Maxfd ; i++) {
84         if (Reserved_fd[i] == fp)
85             break;
86     }
87     if (i >= Maxfd)
88         return fclose(fp);
89     Reserved_fd[i] = freopen("/dev/null", "r", Reserved_fd[i]);
90     return 0;
91 }