为什么rand()在脚本中运行程序时会返回相同的值?

Dim*_*lov 2 c

我srand(time(NULL))在执行开始时有一个,然后我正在做

*pos_x = (rand() % HEIGHT);
*pos_y = (rand() % WIDTH);
Run Code Online (Sandbox Code Playgroud)

生成随机数.

当我手动运行程序时这很好用,但是当我用这个脚本在我的程序中吃午饭时:

#!/bin/bash

i="0"
team_number="0"

while [ $i -lt 30 ]
do
  ./lemipc `pwd` team_number
i=$[$i+1]
  if (( $i % 10 == 0 ))
  then
    team_number=$[$team_number+1]
fi
echo "create process $i"
usleep 10000
done
Run Code Online (Sandbox Code Playgroud)

我总是为所有流程获得相同的数字.

我甚至试图添加一个usleep来解决这个问题,但它仍然无效.我得到这个例子:

97 51 
create process 1
97 51 
create process 2
97 51 
create process 3
97 51 
Run Code Online (Sandbox Code Playgroud)

其中97是pos_x和51 pos_y.

知道为什么吗?

unw*_*ind 7

该time()调用只有全秒精度.如果您的程序都运行相同的秒,它们将使用相同的种子.

你必须添加更多的熵.getpid()如果您拥有它,请考虑使用返回值,或者调查平台的随机源.

  • 建议`srand(time(NULL)^ getpid())` (3认同)