用cat读取:不接收数据时停止

Kai*_*Kai 9 unix linux shell sh cat

有没有办法告诉cat命令在没有收到任何数据时停止阅读?可能有一些"超时",指定没有数据传入多长时间.

有任何想法吗?

pax*_*blo 5

cat本身,没有.它读取输入流,直到告诉它是文件的结尾,必要时阻止输入.

没有什么可以阻止你编写你自己的 cat等价物,select如果没有足够快的东西,将在标准输入上使用超时,并在这些条件下退出.

事实上,我曾经写过一个snail程序(因为蜗牛比猫慢),它每秒花费额外的字符参数来慢慢输出文件(a).

因此每秒snail 10 myprog.c输出myprog.c十个字符.对于我的生活,我不记得为什么我这样做 - 我怀疑我只是在捣乱,等待一些真正的工作出现.

既然你遇到了麻烦,这里有一个版本dog.c(基于我上面提到的snail程序)可以做你想做的事情:

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/select.h>

static int dofile (FILE *fin) {
    int ch = ~EOF, rc;
    fd_set fds;
    struct timeval tv;

    while (ch != EOF) {
        // Set up for fin file, 5 second timeout.

        FD_ZERO (&fds); FD_SET (fileno (fin), &fds);
        tv.tv_sec = 5; tv.tv_usec = 0;
        rc = select (fileno(fin)+1, &fds, NULL, NULL, &tv);
        if (rc < 0) {
            fprintf (stderr, "*** Error on select (%d)\n", errno);
            return 1;
        }
        if (rc == 0) {
            fprintf (stderr, "*** Timeout on select\n");
            break;
        }

        // Data available, so it will not block.

        if ((ch = fgetc (fin)) != EOF) putchar (ch);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

 

int main (int argc, char *argv[]) {
    int argp, rc;
    FILE *fin;

    if (argc == 1)
        rc = dofile (stdin);
    else {
        argp = 1;
        while (argp < argc) {
            if ((fin = fopen (argv[argp], "rb")) == NULL) {
                fprintf (stderr, "*** Cannot open input file [%s] (%d)\n",
                    argv[argp], errno);
                return 1;
            }
            rc = dofile (fin);
            fclose (fin);
            if (rc != 0)
                break;
            argp++;
        }
    }

    return rc;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地运行dog不带参数(因此它将使用标准输入),并且在没有活动的五秒后,它将输出:

*** Timeout on select
Run Code Online (Sandbox Code Playgroud)

(a)实际上,它被称为slowcat但是snail更好,如果它使故事听起来更好,我不会超过一点小修正主义:-)


Mic*_*jer 5

有一个timeout(1)命令.例:

timeout 5s cat /dev/random
Run Code Online (Sandbox Code Playgroud)