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