c - 为什么 rand() 在 fork 之后不是那么随机?

标签 c random fork

#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/

相关文章:

C++ rand() 不适用于字符串数组

c - 在 C 中使用 fork() 调用时程序进入无限循环

c - 实现 FSM 真的需要函数指针吗?

c - 添加变量时出错

c - 指向 char 数组的指针只包含内容的最后几个字母

c - 这是在fork上关闭套接字描述符的正确方法吗?

c - 在 C 中,如何使用 dup2 将 STDOUT_FILENO 重定向到/dev/null,然后再重定向回其原始值?

c++ - 将负数存储在 char 数组中(仍然没有所需/所需的解决方案)

java - 错误: The type of the expression must be an array type but it resolved to int

javascript - 如何在 JavaScript 中生成随机数并将其分配给我的变量数组?