为什么这段代码能测试出父子进程的执行顺序?
最近在看《深入理解计算机系统》(第2版)这本书,看到了第8章异常控制流,对其中的一个程序有些疑惑。
P520页,一个暴露你的代码中竞争的简便技巧:
给出了下面这个程序。说运行这个代码多次,就有极高的概率会测试到父子进程执行的两种顺序
,代码如下:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/time.h>
5 #include <sys/types.h>
6
7 /* Sleep for a random period between [0, MAX_SLEEP] us. */
8 #define MAX_SLEEP 100000
9
10 /* Macro that maps val into the range [0, RAND_MAX] */
11 #define CONVERT(val) (((double)val)/(double)RAND_MAX)
12
13 pid_t Fork(void)
14 {
15 static struct timeval time;
16 unsigned bool, secs;
17 pid_t pid;
18
19 /* Generate a different seed each time the function is called */
20 gettimeofday(&time, NULL);
21 srand(time.tv_usec);
22
23 /* Determine whether to sleep in parent of child and for how long */
24 bool = (unsigned)(CONVERT(rand()) + 0.5);
25 secs = (unsigned)(CONVERT(rand()) * MAX_SLEEP);
26
27 /* Call the real fork function */
28 if ((pid = fork()) < 0)
29 return pid;
30
31 /* Randomly decide to sleep in the parent or the child */
32 if (pid == 0) { /* Child */
33 if(bool) {
34 usleep(secs);
35 }
36 }
37 else { /* Parent */
38 if (!bool) {
39 usleep(secs);
40 }
41 }
42
43 /* Return the PID like a normal fork call */
44 return pid;
45}
本人对为什么这段代码能测试出父子进程的执行顺序还是有些疑惑,求解释!谢谢
小兰·魇魅
12 years, 3 months ago