#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i =10;
/* initialize random seed: */
srand(time(NULL));
while(i--){
if(fork()==0){
/* initialize random seed here does not make a difference:
srand(time(NULL));
*/
printf("%d : %d\n",i,rand());
return;
}
}
return (EXIT_SUCCESS);
}
打印相同(每次运行不同)数字 10 次 - 预期? 我有一段更复杂的代码,其中每个 fork 进程依次运行 - 没有区别
最佳答案
输出必须相同。如果两个进程各自使用相同的种子为随机数播种,并且各自调用一次 rand
,则它们必须得到相同的结果。这就是拥有种子的意义所在。您所有的进程都使用相同的种子调用 srand
(因为您只调用了一次 srand
)并且它们都调用了一次 rand
,所以它们 必须得到相同的结果。
取消对 srand
的注释不会有什么不同,因为除非秒数发生变化,否则它们仍会提供相同的种子。你可以这样做:
srand(time(NULL) ^ (getpid()<<16));
关于c - 为什么 rand() 在 fork 之后不是那么随机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8623131/