Climax Climax - 19 days ago 5
Linux Question

Bash: close if pipe IO is idle

How can I close a program if a pipe stream is idle for a period of time?

Say for instance:

someprogram | closeidlepipe -t 500 | otherprogram


Is there some program
closeidlepipe
that can close if idle for a period (
-t 500
)?

timeout
can close after a period, but not with the "idle" distinction.

UPDATE

It is important to note that
someprogram
outputs an endless stream of binary data. The data may contain the null character
\0
and should be piped verbatim.

Answer

Here's the general form of the heart of a program that does this.

while(1) {
    struct timeval tv;
    tv.m_sec = 0;
    tv.m_usec = 500000;
    int marker = 1;
    select(1, &marker, NULL, NULL, &tv);
    if (marker == 0) exit(1);
    char buf[8192];
    int n = read(0, buf, 8192);
    if (n < 0) exit(2);
    char *b = buf;
    while (n)
    {
        int l = write(1, b, n);
        if (l <= 0) exit(3);
        b += l;
        n -= l;
     }
}
Comments