linux bash中的$ RANDOM在启动时总是一样的 [英] $RANDOM in linux bash will alway be the same upon bootup
问题描述
我遇到了这个问题,我很困惑.
I ran into this problem and I'm so confused.
在Linux启动过程的一开始,我在bash中使用$ RANDOM作为测试字符串.非常有趣的是,我观察到$ RANDOM在每次启动Linux时都是相同的.就我而言,是18869.
I am using $RANDOM in bash as a test string at the very beginning of the linux bootup process. Very interestingly, I observed that $RANDOM will be the same every time linux booted up. In my case, it's 18869.
我只是在文件中回显$ RANDOM.我在每次启动时都观察到了相同的数字.之后,$ RANDOM似乎会返回真实"随机数.
I was simply echoing $RANDOM to a file. I observed the same number in every boot up. After that, $RANDOM seems to return "real" random numbers.
echo "$RANDOM is a test string" >> /tmp/test
有人可以解释其中的原因吗?
Can anyone explain the reason in this?
推荐答案
这是Bash 4.2源代码中 variables.c
的初始种子算法:
Here is the initial seed algorithm from variables.c
in the Bash 4.2 source code:
static void
seedrand ()
{
struct timeval tv;
gettimeofday (&tv, NULL);
sbrand (tv.tv_sec ^ tv.tv_usec ^ getpid ());
}
换句话说,它基于pid和当前时间(以秒和微秒为单位)(系统精度约为1/100秒)来生成种子.
In other words, it generates the seed based on pid and current time in seconds and microseconds (with a system accuracy of ~1/100th second).
如果在可预测的小型系统上检查 $ RANDOM
,则在初始化系统时钟之前,您每次可能会看到相同的值.
If you check $RANDOM
on a small, predictable system, before the system clock is initialized, you're likely to see the same value every time.
这篇关于linux bash中的$ RANDOM在启动时总是一样的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!