chiark / gitweb /
@@ -6,6 +6,8 @@
[chiark-utils.git] / backup / readbuffer.c
1 /*
2  * readbuffer.c
3  *
4  * A program for reading input from devices which don't like constant
5  * stopping and starting, such as tape drives.  readbuffer is:
6  *  Copyright (C) 1997-1998,2000-2001 Ian Jackson <ian@chiark.greenend.org.uk>
7  *
8  * readbuffer is part of chiark backup, a system for backing up GNU/Linux and
9  * other UN*X-compatible machines, as used on chiark.greenend.org.uk.
10  * chiark backup is:
11  *  Copyright (C) 1997-1998,2000-2001 Ian Jackson <ian@chiark.greenend.org.uk>
12  *  Copyright (C) 1999 Peter Maydell <pmaydell@chiark.greenend.org.uk>
13  *
14  * This is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as
16  * published by the Free Software Foundation; either version 2,
17  * or (at your option) any later version.
18  *
19  * This is distributed in the hope that it will be useful, but
20  * WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public
25  * License along with this file; if not, write to the Free Software
26  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  *
28  */
29
30 #include <sys/time.h>
31 #include <sys/types.h>
32 #include <assert.h>
33 #include <fcntl.h>
34 #include <stdio.h>
35 #include <errno.h>
36 #include <unistd.h>
37
38 #include "rwbuffer.h"
39
40 const char *progname= "readbuffer";
41
42 static size_t waitempty;
43
44 int main(int argc, const char *const *argv) {
45   int r,reading;
46
47   startup(argv);
48   waitempty= (buffersize*1)/4;
49   reading=1;
50   
51   while (!seeneof || used) {
52     
53     FD_ZERO(&readfds);
54     if (reading) {
55       if (used<buffersize-1) {
56         FD_SET(0,&readfds);
57       } else {
58         reading=0;
59       }
60     }
61     FD_ZERO(&writefds); if (used) FD_SET(1,&writefds);
62
63     callselect();
64
65     if (FD_ISSET(0,&readfds)) {
66       r= read(0,rp,min(buffersize-1-used,buf+buffersize-rp));
67       if (!r) {
68         seeneof=1; reading=0;
69       } else if (r<0) {
70         if (!(errno == EAGAIN || errno == EINTR)) { perror("read"); exit(1); }
71       } else {
72         used+= r;
73         rp+= r;
74         if (rp == buf+buffersize) rp=buf;
75       }
76     }
77
78     if (FD_ISSET(1,&writefds)) {
79       assert(used);
80       r= write(1,wp,min(used,buf+buffersize-wp));
81       if (r<=0) {
82         if (!(errno == EAGAIN || errno == EINTR)) { perror("write"); exit(1); }
83       } else {
84         used-= r;
85         wp+= r;
86         if (wp == buf+buffersize) wp=buf;
87       }
88       if (used < waitempty && !seeneof) {
89         reading=1;
90       }
91     }
92   }
93   exit(0);
94 }