我正试图找出如何正确使用tee
。在我的应用程序中,由于某种原因,tee
总是返回EINVAL
。我变得绝望了,并试图运行tee
手册页中列出的示例应用程序(例如:https://linux.die.net/man/2/tee),只是发现即使示例代码总是失败:tee: Invalid argument
,例如,当使用它如下:cat tee.c | ./tee tee.log
时。知道为什么会这样吗?
来自die.net的示例代码:
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
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);
}
tee
要求文件描述符fd_in
和fd_out
都需要一个管道。
您的调用没有为第二个文件描述符提供管道,而是为引用TTY的文件描述符提供管道。还要注意手册中的示例特别使用了末尾的| cat
:
The example below implements a basic tee(1) program using the tee() system call.
Here is an example of its use:
$ 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
第二个(或第一个)参数不使用管道文件描述符将符合EINVAL:
EINVAL fd_in or fd_out does not refer to a pipe; or fd_in and fd_out refer to
the same pipe.