Climax Climax - 1 year ago 111
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
that can close if idle for a period (
-t 500

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


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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download