{"id":7448,"date":"2024-09-14T03:00:00","date_gmt":"2024-09-14T07:00:00","guid":{"rendered":"https:\/\/www.both.org\/?p=7448"},"modified":"2024-09-05T15:28:07","modified_gmt":"2024-09-05T19:28:07","slug":"random-numbers-from-the-linux-kernel","status":"publish","type":"post","link":"https:\/\/www.both.org\/?p=7448","title":{"rendered":"Random numbers from the Linux kernel"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"7448\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><\/div>\n<p>I recently shared a <a href=\"https:\/\/www.both.org\/?p=7446\">Guess the number<\/a> game to demonstrate a few \u201cfirst concepts\u201d in C programming. Whenever I learn a new programming language, I like to start with this simple number-guessing game because it exercises the basics of programming, including <em>how to store values in variables<\/em> and <em>how to compare values<\/em>.<\/p>\n\n\n\n<p>That program used the <code>rand<\/code> function to generate <em>pseudo-random<\/em> values between zero and some large maximum value. Pseudo-random numbers are okay if you aren\u2019t working on anything very sensitive\u2014and writing a number-guessing game is pretty straightforward. But if you need to have <a href=\"https:\/\/www.both.org\/?p=6874\">more <em>randomness<\/em><\/a> to the random numbers you generate, you should instead use the <code>getrandom<\/code> system call in the Linux kernel.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"random-bits\">Random bits<\/h2>\n\n\n\n<p>A <em>system call<\/em> acts like a function when you use it in a program, but behind the scenes it interacts directly with the Linux kernel. The <code>getrandom<\/code> system call prompts the kernel to generate a series of random <em>bits<\/em> (ones and zeroes) to \u201cfill\u201d a variable.<\/p>\n\n\n\n<p>Use the <code>getrandom<\/code> system call like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ssize_t getrandom(void buf, size_t buflen, unsigned int flags);<\/code><\/pre>\n\n\n\n<p>The <code>buf<\/code> buffer should be the address to a variable, so the system call can fill this variable directly. The <code>buflen<\/code> value tells <code>getrandom<\/code> how many bytes to fill.<\/p>\n\n\n\n<p>Note that the <code>flags<\/code> value indicates whether the random number should be <em>blocking<\/em> (<code>GRND_RANDOM<\/code>) or <em>nonblocking<\/em> (<code>GRND_NONBLOCK<\/code>). This is important because if the random number source on the system hasn\u2019t been initialized yet, or if the source doesn\u2019t contain enough <em>entropy<\/em>, then using <code>GRND_RANDOM<\/code> with the <code>getrandom<\/code> call will wait for the source to fill up with enough random data before the system call will return its own random bits.<\/p>\n\n\n\n<p>On a desktop system where the user frequently uses the mouse, clicks buttons in apps, and types on the keyboard, the system entropy should be high enough to instantly generate a few bytes of random data. But if you\u2019re not sure, you can use <code>GRND_NONBLOCK<\/code> to prevent blocking, and the system will generate other random bits on its own.<\/p>\n\n\n\n<p>You can see this in action by writing a very short sample program:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n#include &lt;sys\/random.h&gt;\n\nint main()\n{\n  unsigned int num;\n\n  getrandom(&amp;num, sizeof(unsigned int), GRND_NONBLOCK);\n  printf(\"%u\\n\", num);\n\n  return 0;\n}<\/code><\/pre>\n\n\n\n<p>Every time you run the program, the program will use the <code>getrandom<\/code> system call to generate random bits in the <code>num<\/code> variable, which it then prints. Note that <code>getrandom<\/code> creates random bits; if you store the result in a <em>signed<\/em> variable such as a regular <code>int<\/code>, the result could be positive or negative. In this sample, I\u2019ve stored the result in an <em>unsigned<\/em> variable, so the result can only be zero or some other positive number.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"updating-the-number-guessing-program\">Updating the number-guessing program<\/h2>\n\n\n\n<p>With the <code>getrandom<\/code> system call, we can update the <a href=\"https:\/\/www.both.org\/?p=7446\">Guess the number<\/a> program to generate a truly random secret number. If you recall the previous number-guessing program, it used <code>srand<\/code> to <em>seed<\/em> the pseudo-random number generator, and <code>rand<\/code> to generate new pseudo-random numbers. We can replace this by using <code>randval<\/code> to generate random data in a variable, then using the <em>modulo<\/em> (<code>%<\/code>) operator to \u201cfold\u201d the random number into the range 0 to 99, then add 1 to make the secret value between 1 and 100:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    unsigned int randval, secret;\n\n    getrandom(&amp;randval, sizeof(unsigned int), GRND_NONBLOCK);\n    secret = (randval % 100) + 1;<\/code><\/pre>\n\n\n\n<p>Every time you run the program, the Linux kernel will generate random data in the <code>randval<\/code> variable, so the value in <code>secret<\/code> will always be a truly random value between 1 and 100.<\/p>\n\n\n\n<p>The rest of the program is the same. Here\u2019s the completed program:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n#include &lt;sys\/random.h&gt;\n\nint main()\n{\n    unsigned int randval, secret, guess;\n\n    getrandom(&amp;randval, sizeof(unsigned int), GRND_NONBLOCK);\n    secret = (randval % 100) + 1;\n\n    puts(\"Guess a random number from 1 to 100\");\n\n    do {\n        puts(\"Your guess:\");\n        scanf(\"%d\", &amp;guess);\n\n        if (guess &lt; secret) {\n            puts(\"Too low\");\n        }\n        else if (guess &gt; secret) {\n            puts(\"Too high\");\n        }\n    } while (guess != secret);\n\n    puts(\"That's right!\");\n    return 0;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"guess-the-number\">Guess the number<\/h2>\n\n\n\n<p>If we save this updated \u201cGuess the number\u201d program as <code>guess2.c<\/code> we can compile it like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ gcc -o guess2 guess2.c<\/code><\/pre>\n\n\n\n<p>And now we can play the number-guessing game as before. The program will use <code>if<\/code> and <code>else if<\/code> to indicate if the guess is too low or too high, and exit the program with a \u201cThat\u2019s right\u201d message when the guess equals the secret number:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/guess2\nGuess a random number from 1 to 100\nYour guess:\n50\nToo high\nYour guess:\n25\nToo low\nYour guess:\n35\nToo high\nYour guess:\n30\nToo high\nYour guess:\n28\nToo low\nYour guess:\n29\nThat's right!<\/code><\/pre>\n\n\n\n<p>Using <code>srand<\/code> and <code>rand<\/code> is okay if you don\u2019t mind pseudo-random numbers. But if you need to use random values that are <em>actually random<\/em>, you should use the <code>getrandom<\/code> system call instead. Read the manual page (in section 2) to learn more about the <code>getrandom<\/code> system call:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ man 2 getrandom<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Let the kernel generate random numbers for you using &#8216;getrandom.&#8217;<\/p>\n","protected":false},"author":33,"featured_media":3306,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[69,5,150],"tags":[147,91,152],"class_list":["post-7448","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-fun","category-linux","category-programming","tag-fun","tag-linux","tag-programming"],"modified_by":"Jim Hall","_links":{"self":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/7448","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=7448"}],"version-history":[{"count":2,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/7448\/revisions"}],"predecessor-version":[{"id":7450,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/7448\/revisions\/7450"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/media\/3306"}],"wp:attachment":[{"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=7448"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=7448"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=7448"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}