Blob
1 #include <u.h>2 #include <libc.h>3 #include <draw.h>4 #include <thread.h>5 #include <bio.h>6 #include <cursor.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 /*45 * spool standard input to /tmp.46 * we've already read the initial in bytes into ibuf.47 */48 int49 spooltodisk(uchar *ibuf, int in, char **name)50 {51 uchar buf[8192];52 int fd, n;53 char temp[40];55 strcpy(temp, "/tmp/pagespoolXXXXXXXXX");56 fd = opentemp(temp);57 if(name)58 *name = estrdup(temp);60 if(write(fd, ibuf, in) != in){61 fprint(2, "error writing temporary file\n");62 wexits("write temp");63 }65 while((n = read(stdinfd, buf, sizeof buf)) > 0){66 if(write(fd, buf, n) != n){67 fprint(2, "error writing temporary file\n");68 wexits("write temp0");69 }70 }71 seek(fd, 0, 0);72 return fd;73 }75 typedef struct StdinArg StdinArg;77 struct StdinArg {78 Channel *cp;79 uchar *ibuf;80 int in;81 };83 /*84 * spool standard input into a pipe.85 * we've already ready the first in bytes into ibuf86 */87 static void88 _stdinpipe(void *a)89 {90 uchar buf[8192];91 StdinArg *arg;92 int p[2];93 int n;95 arg = a;97 if(pipe(p) < 0){98 fprint(2, "pipe fails: %r\n");99 wexits("pipe");100 }102 send(arg->cp, &p[0]);104 write(p[1], arg->ibuf, arg->in);105 while((n = read(stdinfd, buf, sizeof buf)) > 0)106 write(p[1], buf, n);108 close(p[1]);109 threadexits(0);110 }112 int113 stdinpipe(uchar *ibuf, int in) {114 StdinArg arg;115 int fd;117 arg.ibuf = ibuf;118 arg.in = in;119 arg.cp = chancreate(sizeof(int), 0);120 proccreate(_stdinpipe, &arg, mainstacksize);121 recv(arg.cp, &fd);122 chanfree(arg.cp);124 return fd;125 }