4
$\begingroup$

I am looking to read a few bytes from /dev/random on OS X and Linux. The simplest approach fails on both operating systems (see below).

Why? What is a workaround?

In[1]:= random = OpenRead["/dev/random"]

During evaluation of In[1]:= OpenRead::noopen: Cannot open /dev/random. >>

Out[1]= $Failed

In[2]:= BinaryRead["/dev/random", "Integer32"]

During evaluation of In[2]:= BinaryRead::nffil: File not found during BinaryRead[/dev/random,Integer32]. >>

Out[2]= $Failed
$\endgroup$
6
$\begingroup$

One workaround I found is this:

getRand[] :=
 AbortProtect@Module[{stream, res},
   stream = OpenRead["!head -c 4 /dev/random", BinaryFormat -> True];
   res = BinaryRead[stream, "UnsignedInteger32"];
   Close[stream];
   res
 ]

Tested on OS X and Linux.

$\endgroup$
1
$\begingroup$

read n bytes from /dev/urandom and return a ByteArray:

getrnd[n_Integer /; n >= 1] := 
    ReadByteArray["!dd if=/dev/urandom count=1 bs=" <> ToString[n]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.