112672Ssam #ifndef lint 2*25600Ssam static char *sccsid = "@(#)tee.c 5.4 (Berkeley) 12/14/85"; 312672Ssam #endif 41123Sbill /* 51123Sbill * tee-- pipe fitting 61123Sbill */ 71123Sbill 81123Sbill #include <signal.h> 9*25600Ssam #include <sys/types.h> 10*25600Ssam #include <sys/stat.h> 11*25600Ssam #include <errno.h> 121123Sbill 13*25600Ssam #define BUFSIZ 8192 14*25600Ssam int openf[20] = { 1 }; 15*25600Ssam int n = 1; 16*25600Ssam int t = 0; 17*25600Ssam int aflag; 18*25600Ssam 19*25600Ssam char in[BUFSIZ]; 20*25600Ssam 21*25600Ssam char out[BUFSIZ]; 22*25600Ssam 23*25600Ssam extern errno; 24*25600Ssam long lseek(); 25*25600Ssam 261123Sbill main(argc,argv) 27*25600Ssam char **argv; 281123Sbill { 29*25600Ssam int register r,w,p; 30*25600Ssam struct stat buf; 31*25600Ssam while(argc>1&&argv[1][0]=='-') { 32*25600Ssam switch(argv[1][1]) { 331123Sbill case 'a': 341123Sbill aflag++; 351123Sbill break; 361123Sbill case 'i': 37*25600Ssam case 0: 381123Sbill signal(SIGINT, SIG_IGN); 391123Sbill } 40*25600Ssam argv++; 41*25600Ssam argc--; 421123Sbill } 43*25600Ssam fstat(1,&buf); 44*25600Ssam t = (buf.st_mode&S_IFMT)==S_IFCHR; 45*25600Ssam if(lseek(1,0L,1)==-1&&errno==ESPIPE) 46*25600Ssam t++; 47*25600Ssam while(argc-->1) { 48*25600Ssam if(aflag) { 49*25600Ssam openf[n] = open(argv[1],1); 50*25600Ssam if(openf[n] < 0) 51*25600Ssam openf[n] = creat(argv[1],0666); 52*25600Ssam lseek(openf[n++],0L,2); 53*25600Ssam } else 54*25600Ssam openf[n++] = creat(argv[1],0666); 55*25600Ssam if(stat(argv[1],&buf)>=0) { 56*25600Ssam if((buf.st_mode&S_IFMT)==S_IFCHR) 57*25600Ssam t++; 58*25600Ssam } else { 59*25600Ssam puts("tee: cannot open "); 60*25600Ssam puts(argv[1]); 61*25600Ssam puts("\n"); 62*25600Ssam n--; 63*25600Ssam } 64*25600Ssam argv++; 651123Sbill } 66*25600Ssam r = w = 0; 67*25600Ssam for(;;) { 68*25600Ssam for(p=0;p<BUFSIZ;) { 69*25600Ssam if(r>=w) { 70*25600Ssam if(t>0&&p>0) break; 71*25600Ssam w = read(0,in,BUFSIZ); 72*25600Ssam r = 0; 73*25600Ssam if(w<=0) { 74*25600Ssam stash(p); 75*25600Ssam exit(0); 76*25600Ssam } 77*25600Ssam } 78*25600Ssam out[p++] = in[r++]; 79*25600Ssam } 80*25600Ssam stash(p); 811123Sbill } 821123Sbill } 83*25600Ssam 84*25600Ssam stash(p) 85*25600Ssam { 86*25600Ssam int k; 87*25600Ssam int i; 88*25600Ssam int d; 89*25600Ssam d = t ? 16 : p; 90*25600Ssam for(i=0; i<p; i+=d) 91*25600Ssam for(k=0;k<n;k++) 92*25600Ssam write(openf[k], out+i, d<p-i?d:p-i); 93*25600Ssam } 94*25600Ssam 95*25600Ssam puts(s) 96*25600Ssam char *s; 97*25600Ssam { 98*25600Ssam while(*s) 99*25600Ssam write(2,s++,1); 100*25600Ssam } 101