gpt4 book ai didi

c - 在子进程中生成随机数

转载 作者:行者123 更新时间:2023-11-30 18:38:28 24 4
gpt4 key购买 nike

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

我想要为每个 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();尝试像这样修改您 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>

关于c - 在子进程中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33857568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com