How to rate-limit a pipe under linux?

Pipe Viewer has this feature.

cat /dev/urandom | pv -L 3k | foo

I'd say that Juliano has got the right answer if you have that tool, but I'd also suggest that this is a neat little K&R style exercise: just write a specialized version of cat that reads one character at a time from stdin, outputs each to stdout and then usleeps before moving on. Be sure to unbuffer the standard output, or this will run rather jerkily.

I called this slowcat.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char**argv){
  int c;
  useconds_t stime=10000; // defaults to 100 Hz

  if (argc>1) { // Argument is interperted as Hz
    stime=1000000/atoi(argv[1]);
  }

  setvbuf(stdout,NULL,_IONBF,0);

  while ((c=fgetc(stdin)) != EOF){
    fputc(c,stdout);
    usleep(stime);
  }

  return 0;
}

Compile it and try with

$ ./slowcat 10 < slowcat.c

throttle seems designed specifically for this. e.g.

cat /dev/urandom | throttle -k 3 | foo

Tags:

Linux

Pipe