home *** CD-ROM | disk | FTP | other *** search
- /*
- * keyb -- emulate a user typing at a terminal
- *
- * keyb [ datafile ]
- *
- * standard input is copied to standard output at a rate not in excess
- * of "rate" characters per second, and copied to "copyfile" if
- * specified
- *
- * environment variables $rate and $tty control typing rate (characters
- * per second) and destination of echoed output.
- *
- * $Header: keyb.c,v 3.5 87/06/22 14:24:28 kjmcdonell Beta $
- */
-
- #include <stdio.h>
- #include <signal.h>
-
- #define DEF_RATE 5
- #define GRANULE 5
-
- int thres;
- int est_rate = DEF_RATE;
- int sigpipe; /* pipe write error flag */
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int i;
- int l;
- int fcopy = 0; /* fd for copy output */
- int output; /* aggregate output char count */
- int c;
- int nch; /* # characters read */
- char buf[16]; /* the current glob of data */
- int onalarm();
- int pipeerr();
- char *getenv();
- int written;
- char *p;
- char *prog; /* my name */
-
- prog = argv[0];
- if ((p = getenv("rate")) != (char *)0) {
- sscanf(p, "%f", &est_rate);
- if (est_rate <= 0) {
- fprintf(stderr, "%s: bad rate, reset to %.2f chars/sec\n", prog, DEF_RATE);
- est_rate = DEF_RATE;
- }
- #ifdef DEBUG
- else
- fprintf(stderr, "%s: typing rate %.2f chars/sec\n", est_rate);
- #endif
- }
- if ((p = getenv("tty")) != (char *)0) {
- fcopy = open(p, 1);
- if (fcopy < 0)
- fcopy = creat(p, 0600);
- if (fcopy < 0) {
- fprintf(stderr, "%s: cannot open copy file '%s'\n", prog, p);
- exit(2);
- }
- lseek(fcopy, 0L, 2); /* append at end of file */
- }
-
- if (argc == 2) {
- /* datafile argument specified */
- close(0);
- if (open(argv[1], 0) < 0) {
- fprintf(stderr, "%s: Cannot open %s\n", prog, argv[1]);
- exit(4);
- }
- }
-
- srand(time(0));
- thres = est_rate = est_rate * GRANULE;
- output = 0;
-
- signal(SIGPIPE, pipeerr);
- signal(SIGALRM, onalarm);
- alarm(GRANULE);
- while (1) {
- l = rand() % 15 + 1; /* 1-15 chars */
- if (l == 0) continue;
- nch = read(0, buf, l);
- if (nch == 0)
- break;
- if ((written = write(1, buf, nch)) != nch) {
- /* argh! */
- if (sigpipe)
- fprintf(stderr, "type: ** SIGPIPE error ** buf: %s\n", buf);
- else
- fprintf(stderr, "type: ** write error ** buf: %s\n", buf);
- exit(4);
- }
- if (fcopy)
- write(fcopy, buf, nch);
- output += nch;
- while (output > thres)
- pause();
- }
- alarm(0);
- exit(0);
- }
-
- onalarm()
- {
- thres += est_rate;
- signal(SIGALRM, onalarm);
- alarm(GRANULE);
- }
-
- pipeerr()
- {
- sigpipe++;
- }
-