Last active
October 9, 2015 06:04
-
-
Save ph1ee/554ea4deeda00bde00f0 to your computer and use it in GitHub Desktop.
Delay Pipe: Read a block of data from stdin, write it to stdout with random delay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <unistd.h> | |
| #include <time.h> | |
| #define PIPE_PROGRESS_SIZE 4096 | |
| #define min(a, b) \ | |
| ({ \ | |
| __typeof__(a) _a = (a); \ | |
| __typeof__(b) _b = (b); \ | |
| _a < _b ? _a : _b; \ | |
| }) | |
| static int run(unsigned int maxRead, unsigned int maxDelay, FILE *in, | |
| FILE *out) { | |
| char buf[PIPE_PROGRESS_SIZE]; | |
| size_t len; | |
| setvbuf(out, NULL, _IONBF, 0); | |
| srand(time(NULL)); | |
| // uniform distribution | |
| while ((len = fread(buf, 1, min((rand() % maxRead) + 1, PIPE_PROGRESS_SIZE), | |
| in)) > 0) { | |
| usleep(rand() % maxDelay); | |
| fwrite(buf, 1, len, out); | |
| } | |
| return 0; | |
| } | |
| static void usage(const char *prog) { | |
| fprintf(stderr, "usage: %s [-d <max delay>] [-s <max read>]\n", prog); | |
| exit(EXIT_FAILURE); | |
| } | |
| int main(int argc, char **argv) { | |
| unsigned int maxDelay = 100000; | |
| unsigned int maxRead = 10; | |
| int c; | |
| while ((c = getopt(argc, argv, "d:s:")) != -1) { | |
| switch (c) { | |
| case 'd': | |
| maxDelay = atoi(optarg); | |
| break; | |
| case 's': | |
| maxRead = atoi(optarg); | |
| break; | |
| default: | |
| usage(argv[0]); | |
| } | |
| } | |
| argv += optind; | |
| return run(maxRead, maxDelay, stdin, stdout); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment