binit.c (2130B) download
1#include "lib9.h"
2
3#include <bio.h>
4
5enum {
6 MAXBUFS = 20
7};
8
9static Biobuf* wbufs[MAXBUFS];
10static int atexitflag;
11
12static void
13batexit(void) {
14 Biobuf* bp;
15 int i;
16
17 for (i = 0; i < MAXBUFS; i++) {
18 bp = wbufs[i];
19 if (bp != 0) {
20 wbufs[i] = 0;
21 Bflush(bp);
22 }
23 }
24}
25
26static void
27deinstall(Biobuf* bp) {
28 int i;
29
30 for (i = 0; i < MAXBUFS; i++)
31 if (wbufs[i] == bp)
32 wbufs[i] = 0;
33}
34
35static void
36install(Biobuf* bp) {
37 int i;
38
39 deinstall(bp);
40 for (i = 0; i < MAXBUFS; i++)
41 if (wbufs[i] == 0) {
42 wbufs[i] = bp;
43 break;
44 }
45 if (atexitflag == 0) {
46 atexitflag = 1;
47 atexit(batexit);
48 }
49}
50
51int Binits(Biobuf* bp, int f, int mode, unsigned char* p, int size) {
52
53 p += Bungetsize; /* make room for Bungets */
54 size -= Bungetsize;
55
56 switch (mode & ~(OCEXEC | ORCLOSE | OTRUNC)) {
57 default:
58 fprint(2, "Bopen: unknown mode %d\n", mode);
59 return Beof;
60
61 case OREAD:
62 bp->state = Bractive;
63 bp->ocount = 0;
64 break;
65
66 case OWRITE:
67 install(bp);
68 bp->state = Bwactive;
69 bp->ocount = -size;
70 break;
71 }
72 bp->bbuf = p;
73 bp->ebuf = p + size;
74 bp->bsize = size;
75 bp->icount = 0;
76 bp->gbuf = bp->ebuf;
77 bp->fid = f;
78 bp->flag = 0;
79 bp->rdline = 0;
80 bp->offset = 0;
81 bp->runesize = 0;
82 return 0;
83}
84
85
86int Binit(Biobuf* bp, int f, int mode) {
87 return Binits(bp, f, mode, bp->b, sizeof(bp->b));
88}
89
90Biobuf*
91Bfdopen(int f, int mode) {
92 Biobuf* bp;
93
94 bp = malloc(sizeof(Biobuf));
95 if (bp == 0)
96 return 0;
97 Binits(bp, f, mode, bp->b, sizeof(bp->b));
98 bp->flag = Bmagic;
99 return bp;
100}
101
102Biobuf*
103Bopen(char* name, int mode) {
104 Biobuf* bp;
105 int f;
106
107 switch (mode & ~(OCEXEC | ORCLOSE | OTRUNC)) {
108 default:
109 fprint(2, "Bopen: unknown mode %d\n", mode);
110 return 0;
111
112 case OREAD:
113 f = open(name, mode);
114 if (f < 0)
115 return 0;
116 break;
117
118 case OWRITE:
119 f = create(name, mode, 0666);
120 if (f < 0)
121 return 0;
122 }
123 bp = Bfdopen(f, mode);
124 if (bp == 0)
125 close(f);
126 return bp;
127}
128
129int Bterm(Biobuf* bp) {
130 int ret;
131
132 deinstall(bp);
133 ret = Bflush(bp);
134 if (bp->flag == Bmagic) {
135 bp->flag = 0;
136 if (close(bp->fid) < 0)
137 ret = -1;
138 free(bp);
139 }
140 return ret;
141}