linux - 打印 fifo 内容并退出

标签 linux shell command-line named-pipes

我需要将 fifo(命名管道)的内容打印到标准输出。
我可以使用命令:

cat fifo

问题是 cat 没有返回。它保持运行,等待来自 fifo 的更多内容。但我知道暂时不会有更多内容,所以我只想打印可用的内容。

有没有只打印可用内容然后退出的命令??

编辑:
在 fifo 的一端有一个进程不时写入不同命令的输出。该进程永久运行,因此不会有 EOF。

最佳答案

当您无法发送 EOF 时,您可以使用“非阻塞猫”。我已经包含了一个我发现的(测试过的)C 版本 here (当然要归功于那边的原作者)。神奇之处在于 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK).

这个非阻塞猫的第一个参数是你想在再次退出之前等待的秒数。

#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <string.h>


void read_loop(int fFile, double wWait)
{
    if (fFile < 0) return;

    double max_time = wWait, total_time = 0;
    struct timespec cycle_time = { 0, 50 * 1000 * 1000 };
    double add_time = (double) cycle_time.tv_sec + (double) cycle_time.tv_nsec / 1000000000.;

    char next_line[1024];

    FILE *input_file = fdopen(fFile, "r");

    while (total_time < max_time)
    {
    while (fgets(next_line, 1024, input_file))
     {
    write(STDOUT_FILENO, next_line, strlen(next_line));
    total_time = 0;
     }

    nanosleep(&cycle_time, NULL);
    total_time += add_time;
    }

    fclose(input_file);
}


int main(int argc, char *argv[])
{
    if (argc < 2)
    {
    fprintf(stderr, "%s [max time] (files...)\n", argv[0]);
    return 1;
    }

    int max_wait = strtoul(argv[1],0, 10);

    if (argc == 2)
    {
    fprintf(stderr, "%s: using standard input\n", argv[0]);
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
    read_loop(STDIN_FILENO, max_wait);
    return 0;
    }

    int current = 2;

    while (current < argc)
    {
    fprintf(stderr, "%s: switch to file '%s'\n", argv[0], argv[current]);
    int next_file = open(argv[current++], O_RDONLY | O_NONBLOCK);
    read_loop(next_file, max_wait);
    close(next_file);
    }

    return 0;
}

关于linux - 打印 fifo 内容并退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/865762/

相关文章:

c - 如何在 Linux 上按名称对某些目录中的文件进行排序

c++ - 服务重启后套接字未释放

linux - 为 Linux 命令中的参数提供空值

linux - 复制 bash 目录后,在新目录中编辑文件名?

java - 如何在Windows命令行中正确设置类路径

linux - 如何在 Linux 中打开一个程序的多个实例

shell - julia:命令行的静态分析器/linter

linux - AWS Linux CloudWatch - 前 5 个进程和内存消耗的指标

bash - bash 脚本中奇怪的并行执行

linux - 如何使用 Mahout kmeans 算法将集群转储到本地文件系统