Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: funny subshell effect



On 2011-03-10 at 00:18 +0100, Mikael Magnusson wrote:
> This confused me for a few minutes, I was trying to play a random midi file with
> pmidi *(oe:REPLY=\$RANDOM:[1])
> but it plays the same one each time, but when i tried
> echo *(oe:REPLY=\$RANDOM:[1])
> it printed a different one each time
> 
> % repeat 3; do echo .(e:REPLY=\$RANDOM:); done
> 17
> 25549
> 6369
> % repeat 3; do command echo .(e:REPLY=\$RANDOM:); done
> 5801
> 5801
> 5801
> 
> Is this something that must be so? (My guess is yes, but it can't hurt to ask).
> (I know I can work around it easily by assigning to a var first).

If you assign to RANDOM in the subshell, that's a call to srand() which
will re-seed the RNG.

At present, the retrieval is just:
zlong
randomgetfn(UNUSED(Param pm))
{
    return rand() & 0x7fff;
}

Given the amount of forking going on normally, reseeding on every fork
would be bad, but perhaps something similar to the code I added to Exim
would work, so:

zlong
randomgetfn(UNUSED(Param pm))
{
  static pid_t last_rand_pid = 0;
  pid_t p;

  p = getpid()
  if (p != last_rand_pid)
    {
    last_rand_pid = p;
#ifdef HAVE_SRANDOMDEV_OR_WHATEVER_ZSH_HAS_AS_GUARD
    srandomdev();
#else
    gettimeofday(&tv, NULL);
    srandom(tv.tv_sec | tv.tv_usec | getpid());
#endif
    }
  return rand() & 0x7fff;
}

Except that I actually made Exim prefer arc4random()/arc4random_stir()
if available, and actually uses much stronger randomness from OpenSSL if
linked against that, but that's because people cook up homebrew access
token stuff and I wanted to provide something "not guaranteed
cryptographically strong, but at least not a complete nightmare".

Anyway, does this look like a reasonable approach?

-Phil



Messages sorted by: Reverse Date, Date, Thread, Author