blind

suckless command-line video editing utility
git clone git://git.suckless.org/blind
Log | Files | Refs | README | LICENSE

blind-tee.c (985B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include "common.h"
      3 
      4 USAGE("[file ...]")
      5 
      6 int
      7 main(int argc, char *argv[])
      8 {
      9 	char buf[PIPE_BUF];
     10 	int *fds = alloca((size_t)argc * sizeof(*fds));
     11 	size_t i, n = 0, done;
     12 	ssize_t r, w, *ps;
     13 
     14 	UNOFLAGS(0);
     15 
     16 	signal(SIGPIPE, SIG_IGN);
     17 
     18 	fds[n++] = STDOUT_FILENO;
     19 	while (argc--)
     20 		fds[n++] = eopen(*argv++, O_WRONLY | O_CREAT | O_TRUNC, 0666);
     21 
     22 	ps = alloca(n * sizeof(*ps));
     23 
     24 	while (n) {
     25 		memset(ps, 0, n * sizeof(*ps));
     26 		r = read(STDIN_FILENO, buf, sizeof(buf));
     27 		if (r < 0)
     28 			eprintf("read <stdin>:");
     29 		if (!r)
     30 			break;
     31 		for (done = 0; done < n;) {
     32 			for (i = 0; i < n; i++) {
     33 				if (ps[i] == r)
     34 					continue;
     35 				w = write(fds[i], buf + ps[i], (size_t)(r - ps[i]));
     36 				if (w < 0) {
     37 					close(fds[i]);
     38 					n--;
     39 					memmove(fds + i, fds + i + 1, (n - i) * sizeof(*fds));
     40 					memmove(ps  + i, ps  + i + 1, (n - i) * sizeof(*ps));
     41 				}
     42 				ps[i] += w;
     43 				if (ps[i] == r)
     44 					done++;
     45 			}
     46 		}
     47 	}
     48 
     49 	return 0;
     50 }