xref: /csrg-svn/usr.bin/tee/tee.c (revision 51971)
1 /*
2  * Copyright (c) 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1988 Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)tee.c	5.12 (Berkeley) 12/16/91";
16 #endif /* not lint */
17 
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 
27 typedef struct _list {
28 	struct _list *next;
29 	int fd;
30 	char *name;
31 } LIST;
32 LIST *head;
33 
34 main(argc, argv)
35 	int argc;
36 	char **argv;
37 {
38 	extern int errno, optind;
39 	register LIST *p;
40 	register int n, fd, rval, wval;
41 	register char *bp;
42 	int append, ch, exitval;
43 	char *buf;
44 	off_t lseek();
45 #define	BSIZE (8 * 1024)
46 
47 	append = 0;
48 	while ((ch = getopt(argc, argv, "ai")) != EOF)
49 		switch((char)ch) {
50 		case 'a':
51 			append = 1;
52 			break;
53 		case 'i':
54 			(void)signal(SIGINT, SIG_IGN);
55 			break;
56 		case '?':
57 		default:
58 			(void)fprintf(stderr, "usage: tee [-ai] [file ...]\n");
59 			exit(1);
60 		}
61 	argv += optind;
62 	argc -= optind;
63 
64 	if (!(buf = malloc((u_int)BSIZE))) {
65 		(void)fprintf(stderr, "tee: out of space.\n");
66 		exit(1);
67 	}
68 	add(STDOUT_FILENO, "stdout");
69 	for (; *argv; ++argv)
70 		if ((fd = open(*argv, append ? O_WRONLY|O_CREAT|O_APPEND :
71 		    O_WRONLY|O_CREAT|O_TRUNC, DEFFILEMODE)) < 0)
72 			(void)fprintf(stderr, "tee: %s: %s.\n",
73 			    *argv, strerror(errno));
74 		else
75 			add(fd, *argv);
76 	exitval = 0;
77 	while ((rval = read(STDIN_FILENO, buf, BSIZE)) > 0)
78 		for (p = head; p; p = p->next) {
79 			n = rval;
80 			bp = buf;
81 			do {
82 				if ((wval = write(p->fd, bp, n)) == -1) {
83 					(void)fprintf(stderr, "tee: %s: %s.\n",
84 					    p->name, strerror(errno));
85 					exitval = 1;
86 					break;
87 				}
88 				bp += wval;
89 			} while (n -= wval);
90 		}
91 	if (rval < 0) {
92 		(void)fprintf(stderr, "tee: read: %s\n", strerror(errno));
93 		exit(1);
94 	}
95 	exit(exitval);
96 }
97 
98 add(fd, name)
99 	int fd;
100 	char *name;
101 {
102 	LIST *p;
103 
104 	if (!(p = malloc((u_int)sizeof(LIST)))) {
105 		(void)fprintf(stderr, "tee: out of space.\n");
106 		exit(1);
107 	}
108 	p->fd = fd;
109 	p->name = name;
110 	p->next = head;
111 	head = p;
112 }
113