#define _GNU_SOURCE /* feature_test_macros(7) 参照 */ #include <fcntl.h> ssize_t tee(int fd_in, int fd_out, size_t len, unsigned int flags);
flags is a bit mask that is composed by ORing together zero or more of the following values:
エラーの場合、 tee() は -1 を返し、 errno にエラーを示す値を設定する。
$ date |./a.out out.log | cat Tue Oct 28 10:06:00 CET 2014 $ cat out.log Tue Oct 28 10:06:00 CET 2014
int
main(int argc, char *argv[])
{
int fd;
int len, slen;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
do {
/*
* tee stdin to stdout.
*/
len = tee(STDIN_FILENO, STDOUT_FILENO,
INT_MAX, SPLICE_F_NONBLOCK);
if (len < 0) {
if (errno == EAGAIN)
continue;
perror("tee");
exit(EXIT_FAILURE);
} else
if (len == 0)
break;
/*
* Consume stdin by splicing it to a file.
*/
while (len > 0) {
slen = splice(STDIN_FILENO, NULL, fd, NULL,
len, SPLICE_F_MOVE);
if (slen < 0) {
perror("splice");
break;
}
len -= slen;
}
} while (1);
close(fd);
exit(EXIT_SUCCESS);
}