Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <draw.h>
4 #include <cursor.h>
5 #include <event.h>
6 #include <bio.h>
7 #include "page.h"
9 void*
10 emalloc(int sz)
11 {
12 void *v;
13 v = malloc(sz);
14 if(v == nil) {
15 fprint(2, "out of memory allocating %d\n", sz);
16 wexits("mem");
17 }
18 memset(v, 0, sz);
19 return v;
20 }
22 void*
23 erealloc(void *v, int sz)
24 {
25 v = realloc(v, sz);
26 if(v == nil) {
27 fprint(2, "out of memory allocating %d\n", sz);
28 wexits("mem");
29 }
30 return v;
31 }
33 char*
34 estrdup(char *s)
35 {
36 char *t;
37 if((t = strdup(s)) == nil) {
38 fprint(2, "out of memory in strdup(%.10s)\n", s);
39 wexits("mem");
40 }
41 return t;
42 }
44 int
45 opentemp(char *template)
46 {
47 int fd, i;
48 char *p;
50 p = estrdup(template);
51 fd = -1;
52 for(i=0; i<10; i++){
53 mktemp(p);
54 if(access(p, 0) < 0 && (fd=create(p, ORDWR|ORCLOSE, 0400)) >= 0)
55 break;
56 strcpy(p, template);
57 }
58 if(fd < 0){
59 fprint(2, "couldn't make temporary file\n");
60 wexits("Ecreat");
61 }
62 strcpy(template, p);
63 free(p);
65 return fd;
66 }
68 /*
69 * spool standard input to /tmp.
70 * we've already read the initial in bytes into ibuf.
71 */
72 int
73 spooltodisk(uchar *ibuf, int in, char **name)
74 {
75 uchar buf[8192];
76 int fd, n;
77 char temp[40];
79 strcpy(temp, "/tmp/pagespoolXXXXXXXXX");
80 fd = opentemp(temp);
81 if(name)
82 *name = estrdup(temp);
84 if(write(fd, ibuf, in) != in){
85 fprint(2, "error writing temporary file\n");
86 wexits("write temp");
87 }
89 while((n = read(stdinfd, buf, sizeof buf)) > 0){
90 if(write(fd, buf, n) != n){
91 fprint(2, "error writing temporary file\n");
92 wexits("write temp0");
93 }
94 }
95 seek(fd, 0, 0);
96 return fd;
97 }
99 /*
100 * spool standard input into a pipe.
101 * we've already ready the first in bytes into ibuf
102 */
103 int
104 stdinpipe(uchar *ibuf, int in)
106 uchar buf[8192];
107 int n;
108 int p[2];
109 if(pipe(p) < 0){
110 fprint(2, "pipe fails: %r\n");
111 wexits("pipe");
114 switch(rfork(RFPROC|RFFDG)){
115 case -1:
116 fprint(2, "fork fails: %r\n");
117 wexits("fork");
118 default:
119 close(p[1]);
120 return p[0];
121 case 0:
122 break;
125 close(p[0]);
126 write(p[1], ibuf, in);
127 while((n = read(stdinfd, buf, sizeof buf)) > 0)
128 write(p[1], buf, n);
130 _exits(0);
131 return -1; /* not reached */