util.c 2.0 KB

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