chiark / gitweb /
better error docs
[chiark-utils.git] / cprogs / rwbuffer.c
index d91a96eb639fc42dc8fdb3833456bf8fc164f647..f2ec48da0e5a00086b8884e8e1afc0de36f8d6d7 100644 (file)
  *
  */
 
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <assert.h>
-#include <ctype.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <sys/mman.h>
-
 #include "rwbuffer.h"
 
 #ifndef RWBUFFER_SIZE_MB_DEF
 #endif
 
 unsigned char *buf, *wp, *rp;
-int used, seeneof;
+int used, seeneof, maxselfd;
 size_t buffersize;
 fd_set readfds;
 fd_set writefds;
 
+static int opt_mlock=0;
+
 int min(int a, int b) { return a<=b ? a : b; }
 
 static void usage(FILE *f) {
@@ -67,7 +58,7 @@ static void usageerr(const char *what) {
   exit(12);
 }
 
-static void nonblock(int fd, int yesno) {
+void nonblock(int fd, int yesno) {
   int r;
   r= fcntl(fd,F_GETFL,0); if (r == -1) { perror("fcntl getfl"); exit(8); }
   if (yesno) r |= O_NDELAY;
@@ -79,11 +70,21 @@ static void unnonblock(void) {
   nonblock(0,0); nonblock(1,0);
 }
 
+void startupcore(void) {
+  buf= xmalloc(buffersize);
+
+  if (opt_mlock) {
+    if (mlock(buf,buffersize)) { perror("mlock"); exit(2); }
+  }
+
+  used=0; wp=rp=buf; seeneof=0;
+  if (atexit(unnonblock)) { perror("atexit"); exit(16); }
+}
+
 void startup(const char *const *argv) {
   const char *arg;
   char *ep;
   unsigned long opt_buffersize=RWBUFFER_SIZE_MB_DEF;
-  int opt_mlock=0;
   
   assert(argv[0]);
   
@@ -100,14 +101,7 @@ void startup(const char *const *argv) {
   }
 
   buffersize= opt_buffersize*1024*1024;
-  buf= xmalloc(buffersize);
-
-  if (opt_mlock) {
-    if (mlock(buf,buffersize)) { perror("mlock"); exit(2); }
-  }
-
-  used=0; wp=rp=buf; seeneof=0;
-  if (atexit(unnonblock)) { perror("atexit"); exit(16); }
+  startupcore();
   nonblock(0,1); nonblock(1,1);
 }
 
@@ -119,7 +113,7 @@ void callselect(void) {
   int r;
   
   for (;;) {
-    r= select(2,&readfds,&writefds,0,0);
+    r= select(maxselfd,&readfds,&writefds,0,0);
     if (r != -1) return;
     if (errno != EINTR) {
       perror("select"); exit(4);