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