Hacker News new | ask | show | jobs
by DHowett 5211 days ago
The only caveat is that you then have to wrap it in an #ifdef if you want source portability. The thing random() has over arc4random() is exactly that - it's part of the standard C library on most platforms.

For discussion: Why is random() not already arc4random() on platforms that provide the arc4 variant? Is it for speed's sake? Different implementations of libc functions will seed differently, so it's not a cross-platform seed stability concern. Is the problem that you can't seed it with a fixed value and get the same pseudorandom sequence?

1 comments

Yes, because of the need for pseudorandom sequences. In FreeBSD this comes up every so often, but the reality is that there's a lot of AI and simulation/modeling code that uses the libc random functions (either rand(3) or random(3)) and expects reproducible behavior with the same seed both throughout the life of a program and across multiple executions.
That could easily be accommodated by implementing random_ng() to take an optional buffer that the PRNG would use to initialize its state. If a buffer is not passed, use a random or pseudorandom entropy source... whatever's available on the system. From ivy bridge on, intel cpus will have the RdRand instruction, or there's /dev/urandom.

That offers the best of both worlds. If you want repeatably, initialize random_ng() with a known buffer. If you want reasonable unpredictability, let the PRNG initialize itself using whatever it wants. (Not to confuse that PRNG with good entropy randomness that might be accessible from RdRand, or which is usually obtained by asking the user to move the mouse.)

Right, and there are other RNG and PRNG sources and interfaces for precisely that reaon. The question was why random(3) isn't arc4random(3).