sbase

suckless unix tools
git clone git://git.suckless.org/sbase
Log | Files | Refs | README | LICENSE

tee.c (1061B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <fcntl.h>
      3 #include <signal.h>
      4 #include <unistd.h>
      5 
      6 #include "util.h"
      7 
      8 static void
      9 usage(void)
     10 {
     11 	eprintf("usage: %s [-ai] [file ...]\n", argv0);
     12 }
     13 
     14 int
     15 main(int argc, char *argv[])
     16 {
     17 	int *fds = NULL;
     18 	size_t i, nfds;
     19 	ssize_t n;
     20 	int ret = 0, aflag = O_TRUNC, iflag = 0;
     21 	char buf[BUFSIZ];
     22 
     23 	ARGBEGIN {
     24 	case 'a':
     25 		aflag = O_APPEND;
     26 		break;
     27 	case 'i':
     28 		iflag = 1;
     29 		break;
     30 	default:
     31 		usage();
     32 	} ARGEND
     33 
     34 	if (iflag && signal(SIGINT, SIG_IGN) == SIG_ERR)
     35 		eprintf("signal:");
     36 	nfds = argc + 1;
     37 	fds = ecalloc(nfds, sizeof(*fds));
     38 
     39 	for (i = 0; i < argc; i++) {
     40 		if ((fds[i] = open(argv[i], O_WRONLY|O_CREAT|aflag, 0666)) < 0) {
     41 			weprintf("open %s:", argv[i]);
     42 			ret = 1;
     43 		}
     44 	}
     45 	fds[i] = 1;
     46 
     47 	while ((n = read(0, buf, sizeof(buf))) > 0) {
     48 		for (i = 0; i < nfds; i++) {
     49 			if (fds[i] >= 0 && writeall(fds[i], buf, n) < 0) {
     50 				weprintf("write %s:", (i != argc) ? argv[i] : "<stdout>");
     51 				fds[i] = -1;
     52 				ret = 1;
     53 			}
     54 		}
     55 	}
     56 	if (n < 0)
     57 		eprintf("read <stdin>:");
     58 
     59 	return ret;
     60 }