#include #include #include #include #include #include #include #include "config.h" int main(int argc, char **argv) { int flag = O_TRUNC; int opt; while ((opt = getopt(argc, argv, "ai")) != -1) { switch (opt) { case 'a': flag = O_APPEND; break; case 'i': signal(SIGINT, SIG_IGN); break; default: puts("tee [ai] [file]\n\t-a Append\n\t-i Ignore interrupt signals"); return 0; } } argv += optind; argc -= optind; int fd = STDOUT_FILENO; if (argc > 0 && strcmp(argv[0], "-")) { fd = open(argv[0], O_WRONLY | flag | O_CREAT, 0666); if (fd < 0) { fprintf(stderr, "tee: %s\n", strerror(errno)); return 1; } } char buf[BUF_SIZE + 1]; ssize_t bytes = 0; while ((bytes = read(STDIN_FILENO, buf, sizeof(buf)))) { int stat = write(STDOUT_FILENO, buf, bytes); int stat2 = bytes; if (argc > 0) stat2 = write(fd, buf, bytes); if (stat != bytes || stat2 != bytes) { fprintf(stderr, "tee: %s\n", strerror(errno)); return 1; } } if (argc > 0 && strcmp(argv[0], "-")) close(fd); return 0; }