c - tee 总是返回 EINVAL

标签 c linux

我正在尝试弄清楚如何正确使用 tee。在我的应用程序中,tee 出于某种原因总是返回 EINVAL。我感到绝望,并尝试运行 tee 手册页中列出的示例应用程序(例如:https://linux.die.net/man/2/tee),却发现即使是该示例代码也总是失败:tee: 无效参数,例如在如下使用时: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_infd_out

您的调用不为第二个文件描述符提供管道,而是提供引用 TTY 的文件描述符。另请注意,联机帮助页中的示例专门使用尾随 |猫:

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.

关于c - tee 总是返回 EINVAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438434/

相关文章:

范围内的恒定时间随机数

c - free() 崩溃,但前提是分配的内存超过一定大小

c++ - 延迟共享库的链接

linux - 如何合并两个 .so 库

linux - 用于查找硬件信息的 Bash 脚本给出 "Memory Fault"

c - 如何获得返回字符串的函数?

c++ - 与legendre公式相关的程序异常

c - 内存分配。二维数组(空函数)

python - zeromq 同时订阅和发布

linux - 为 OpenWrt 编写和编译程序