#define _GNU_SOURCE /* feature_test_macros(7) 参照 */ #include <fcntl.h> ssize_t tee(int fd_in, int fd_out, size_t size, 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
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
int fd;
ssize_t size, ssize;
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);
}
for (;;) {
/*
* tee stdin to stdout.
*/
size = tee(STDIN_FILENO, STDOUT_FILENO,
INT_MAX, SPLICE_F_NONBLOCK);
if (size < 0) {
if (errno == EAGAIN)
continue;
perror("tee");
exit(EXIT_FAILURE);
}
if (size == 0)
break;
/*
* Consume stdin by splicing it to a file.
*/
while (size > 0) {
ssize = splice(STDIN_FILENO, NULL, fd, NULL,
size, SPLICE_F_MOVE);
if (ssize < 0) {
perror("splice");
exit(EXIT_FAILURE);
}
size -= ssize;
}
}
close(fd);
exit(EXIT_SUCCESS);
}