If you are writing a game, a simulation, a statistical model or, heaven forbid, rolling your own encryption, then you will probably want some random numbers. There is no way for your computer to provide random numbers in the same way that you can from a fair coin-toss or dice-roll but there are many ways to get what are called pseudorandom numbers. Pseudorandom numbers are not truly random but they are chaotic and difficult to predict. Linux provides random numbers in two ways, via /dev/random and /dev/urandom.

The character device /dev/urandom will give a constant stream of pseudorandom numbers on demand. Try executing od /dev/urandom in your terminal to see the random bytes it outputs. The device can output a stream of numbers indefinitely.

The other random number device /dev/random is used differently. If you do od /dev/random you will notice it output numbers for a while and then stop. This is because it generates its numbers by drawing from a 'pool' of randomness that is kept in the kernel. This pool collects events which are considered random, such as time between keystrokes and mouse movements. When /dev/random wants to generate a number it takes some entropy from the pool and use it to make the pseudorandom number it generates less predictable. However, once the pool has run out of entropy /dev/random will stop outputting numbers until some more entropy is available. Try running od /dev/random until the numbers stop and then watch then start up again by jiggling your mouse around. If you have ever generated a large gpg key then you will know what it is like to run out of entropy and need to jiggle your mouse around for a while. There do exist other ways to refill your entropy pool.

Incidentally, /dev/urandom also uses entropy from the same pool if entropy is available but if none is available then numbers will be generated using an iterative process with no entropy involved.

It is useful to have an idea of how linux does random numbers but when writing a program it is unlikely that you will use /dev/random or /dev/urandom directly; practically all modern programming languages provide you with some way of getting random numbers. Python, for example, asks /dev/urandom for random numbers when you use the random module. It is also worth mentioning that a lot of programming languages will have their own pseudorandom number generators and not rely on the Linux kernel at all. Such generators are many and varied and will the covered in a future article.