在 child 过程中生成随机数

Generate randoms in child process

在下面的代码中,我做了一堆分叉,每个 child 生成一个随机值,但是当我执行代码时,随机值在所有 child 中都是相同的。为什么会发生这种情况,我该如何解决?

我想要每个 child 的不同随机值。

for (i=0; i<n; i++) {
        ret = fork();
        if (ret == 0) {
            /* child process*/

                    read(descriptor_fitxer[i][0], missatge, 50);
                    randomvalue = rand() % 50;
                    printf("Random is %d",randomvalue)
                    exit(0);


            }else{
            /*dad process*/
             wait(&st);}

输出:

Random is 31
Random is 31
Random is 31
Random is 31
Random is 31
Random is 31
Random is 31
Random is 31
Random is 31
Random is 31

您需要使用 srand() 作为伪随机数生成器的种子。 添加

srand((unsigned int)(time(0) + i*i));

在调用 rand().

之前

通常,您只需调用 srand() 一次即可播种。但是如果你在循环之前只播种一次,那么 rand() 将是相同的数字序列(这就是 rand 设计的工作方式)。所以在 each 过程中播种是必要的。

在循环内调用 srand((unsigned int)(time(0))); 可能仍然会遇到同样的问题,因为循环可能 运行 足够快以获得相同的种子。所以我使用 i*i 以防万一。

你在哪里以及如何使用 srand(); 尝试像这样修改 child 的代码

            read(descriptor_fitxer[i][0], missatge, 50);
            srand(time(NULL)+i);
            randomvalue = rand() % 50;
            printf("Random is %d",randomvalue)
            exit(0);

也一定要做到#include <time.h>