1 /* $NetBSD: rand_sleep.c,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $ */ 2 3 /*++ 4 /* NAME 5 /* rand_sleep 3 6 /* SUMMARY 7 /* sleep for randomized interval 8 /* SYNOPSIS 9 /* #include <iostuff.h> 10 /* 11 /* void rand_sleep(delay, variation) 12 /* unsigned delay; 13 /* unsigned variation; 14 /* DESCRIPTION 15 /* rand_sleep() blocks the current process for an amount of time 16 /* pseudo-randomly chosen from the interval (delay +- variation/2). 17 /* 18 /* Arguments: 19 /* .IP delay 20 /* Time to sleep in microseconds. 21 /* .IP variation 22 /* Variation in microseconds; must not be larger than delay. 23 /* DIAGNOSTICS 24 /* Panic: interface violation. All system call errors are fatal. 25 /* LICENSE 26 /* .ad 27 /* .fi 28 /* The Secure Mailer license must be distributed with this software. 29 /* AUTHOR(S) 30 /* Wietse Venema 31 /* IBM T.J. Watson Research 32 /* P.O. Box 704 33 /* Yorktown Heights, NY 10598, USA 34 /*--*/ 35 36 /* System library. */ 37 38 #include <sys_defs.h> 39 #include <stdlib.h> 40 #include <unistd.h> 41 #include <time.h> 42 43 /* Utility library. */ 44 45 #include <msg.h> 46 #include <myrand.h> 47 #include <iostuff.h> 48 49 /* rand_sleep - block for random time */ 50 51 void rand_sleep(unsigned delay, unsigned variation) 52 { 53 const char *myname = "rand_sleep"; 54 unsigned usec; 55 56 /* 57 * Sanity checks. 58 */ 59 if (delay == 0) 60 msg_panic("%s: bad delay %d", myname, delay); 61 if (variation > delay) 62 msg_panic("%s: bad variation %d", myname, variation); 63 64 /* 65 * Use the semi-crappy random number generator. 66 */ 67 usec = (delay - variation / 2) + variation * (double) myrand() / RAND_MAX; 68 doze(usec); 69 } 70 71 #ifdef TEST 72 73 #include <msg_vstream.h> 74 75 int main(int argc, char **argv) 76 { 77 int delay; 78 int variation; 79 80 msg_vstream_init(argv[0], VSTREAM_ERR); 81 if (argc != 3) 82 msg_fatal("usage: %s delay variation", argv[0]); 83 if ((delay = atoi(argv[1])) <= 0) 84 msg_fatal("bad delay: %s", argv[1]); 85 if ((variation = atoi(argv[2])) < 0) 86 msg_fatal("bad variation: %s", argv[2]); 87 rand_sleep(delay * 1000000, variation * 1000000); 88 exit(0); 89 } 90 91 #endif 92