/* * Title: Slowpipe.C * * Description: Bandwidth restriction for UNIX pipes * * This software may be freely redistrubuted providing this comment remains * unchanged. * * Author: Iain W. Bird, http://www.birdsoft.demon.co.uk * wes@birdsoft.demon.co.uk */ #include #include #include #include main(int argc, char **argv) { FILE *fd; char c; char *buffer; int bufsiz = 16; int i; int sleep = 0; int full = 0; struct timeval tval; double kps = 2.0,bps,pps; unsigned long t_s, t_us; if(argc != 2) { perror("Usage slowpipe "); exit(1); } sscanf(argv[1],"%lg",&kps); if ( kps > 10.0 ) { bufsiz = 1024; } else if ( kps > 5.0 ) { bufsiz = 512; } else if ( kps > 2.0 ) { bufsiz = 256; } else if ( kps > 1.0 ) { bufsiz = 128; } else if ( kps > 0.5 ) { bufsiz = 64; } bps = 1024.0 * kps; pps = bps / bufsiz; if(pps > 1.0) { t_s = 0.0; t_us= 1.0e6 / pps; } else { t_s = 1.0 / pps; t_us = 0; } fprintf(stderr,"%6.2g K per second, bufsiz = %d\n",kps,bufsiz); buffer = malloc(bufsiz); if(!buffer) { perror("Unable to allocate buffer"); exit(1); } i = 0; while (1) { if (!full) { if(i < bufsiz) { buffer[i] = fgetc(stdin); if(feof(stdin)) { fwrite(buffer,1,i,stdout); break; } if(++i == bufsiz) { full = !0; } } } else { /* go for a blocking select since the buffer is full */ tval.tv_sec = t_s; tval.tv_usec = t_us; select ( 0, 0, 0, 0, &tval ); fwrite(buffer,1,bufsiz,stdout); full = 0; i = 0; } } free(buffer); }