<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vadher Nikunj on Medium]]></title>
        <description><![CDATA[Stories by Vadher Nikunj on Medium]]></description>
        <link>https://medium.com/@vadhernknj19?source=rss-56ff44f2eb9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Vadher Nikunj on Medium</title>
            <link>https://medium.com/@vadhernknj19?source=rss-56ff44f2eb9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:34:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vadhernknj19/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Structs Inside Structs in C: Nesting, Memory and container_of (Linux Kernel Examples)]]></title>
            <link>https://medium.com/@vadhernknj19/structs-inside-structs-in-c-nesting-memory-and-container-of-linux-kernel-examples-9f0d4567976b?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f0d4567976b</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 07:25:31 GMT</pubDate>
            <atom:updated>2026-11-27T07:25:31.793Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post was first published on </em><a href="https://www.jupiuslearning.com/blog/c-structs-inside-structs-nesting-container-of-linux-kernel/"><em>Jupius Learning</em></a><em>, where you can read it free with diagrams and practice exercises.</em></p><p><a href="https://www.jupiuslearning.com/blog/#subscribe"><em>Subscribe to our articles for regular updates</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IGH5CdurP9nGgwFV.png" /></figure><p>You can put a struct inside another struct, as a field. The inner struct sits in memory as a block, with its own padding. The outer struct may have padding around that block too. The padding rules from the <a href="https://www.jupiuslearning.com/blog/c-struct-padding-alignment-memory-linux-kernel/">last post</a> still apply, one level down.</p><p>In the <a href="https://www.jupiuslearning.com/blog/your-first-c-struct-declare-fill-read-linux-kernel/">first post of this series</a> we declared a struct student, filled it and read it. This time we give that student an address, itself a struct, and we look at how the Linux kernel builds bigger structs out of smaller ones. That includes a small trick called container_of, which takes the address of an inner field and gives you back the outer struct.</p><p>All the sizes in this post come from gcc on a 64-bit x86 Linux machine. I compiled and ran every program shown here. On a different CPU or compiler a few numbers may change, and I will point out where.</p><h3>How do you put a struct inside another struct?</h3><p>First declare the inner type, then use it as a field of the outer type. Here is the student struct from earlier in the series, with a new addr field.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stddef.h&gt;<br>#include &lt;string.h&gt;</pre><pre>struct address {<br>    char city[20];<br>    int  pin;<br>};</pre><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>    struct address addr;<br>};</pre><pre>int main(void)<br>{<br>    struct student s1;</pre><pre>    s1.roll_no = 1;<br>    strcpy(s1.name, &quot;Asha&quot;);<br>    s1.marks = 88.5f;<br>    strcpy(s1.addr.city, &quot;Pune&quot;);<br>    s1.addr.pin = 411001;</pre><pre>    printf(&quot;sizeof(struct address) = %zu\n&quot;, sizeof(struct address));<br>    printf(&quot;sizeof(struct student) = %zu\n&quot;, sizeof(struct student));<br>    printf(&quot;city at offset %zu\n&quot;, offsetof(struct address, city));<br>    printf(&quot;pin  at offset %zu\n&quot;, offsetof(struct address, pin));<br>    printf(&quot;addr at offset %zu\n&quot;, offsetof(struct student, addr));<br>    printf(&quot;%s, pin %d\n&quot;, s1.addr.city, s1.addr.pin);<br>    return 0;<br>}</pre><p>Save it as student_nested.c, then compile and run it:</p><pre>gcc student_nested.c -o student_nested<br>./student_nested</pre><p>In PowerShell with MinGW, run it with .\student_nested.exe.</p><p>Output:</p><pre>sizeof(struct address) = 24<br>sizeof(struct student) = 84<br>city at offset 0<br>pin  at offset 20<br>addr at offset 60<br>Pune, pin 411001</pre><p>addr is a value, not a pointer. The 24 bytes of the address live inside the student. When you copy a struct student, the city and pin go with it.</p><p>The fields of struct address add up to 20 + 4 = 24 bytes, and sizeof is also 24. There is no hole this time. city is 20 bytes, and 20 is already a multiple of 4, so pin can start right at offset 20.</p><p>The student struct in the <a href="https://www.jupiuslearning.com/blog/c-struct-padding-alignment-memory-linux-kernel/">padding post</a> was 60 bytes. Adding a 24 byte addr at offset 60 makes it 84. The two padding bytes before marks are still there. Nesting did not remove them.</p><h3>Named member or an inline definition</h3><p>The usual way, which I will use for the rest of this post, is the one above. You declare struct address on its own, then write struct address addr; as a field. The member has a name, addr, and the type has a name too. You can make a standalone struct address variable, pass it to a function, or use it in more than one outer struct.</p><p>You can also write the inner struct in place, at the same time as you declare the field:</p><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>    struct {<br>        char city[20];<br>        int  pin;<br>    } addr;<br>};</pre><p>You still write s1.addr.city and s1.addr.pin. The difference is that this inner type has no tag of its own, so you cannot declare a separate struct address variable. If you only need this shape inside struct student, that is fine. If you want to reuse the address type, give it a name first.</p><p>If you leave out the member name as well, the inner fields belong to the outer struct. You would then write s1.city and s1.pin, with no addr in between. gcc and C11 allow this. It can be handy, but it also hides the fact that those fields arrived as a group, so I prefer a named member for examples like this one.</p><h3>How a nested struct sits in memory</h3><p>The inner struct is laid out first, with the same alignment rules as any other struct. Then that whole block is placed in the outer struct. The block must start at an offset that is a multiple of the inner struct’s own alignment, which is the alignment of its strictest field.</p><p>That is easier to see with a smaller example, because the holes are right next to the fields.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stddef.h&gt;</pre><pre>struct inner {<br>    char a;<br>    int  b;<br>};</pre><pre>struct outer {<br>    char flag;<br>    struct inner nest;<br>    int  id;<br>};</pre><pre>int main(void)<br>{<br>    printf(&quot;sizeof(struct inner) = %zu\n&quot;, sizeof(struct inner));<br>    printf(&quot;a at %zu, b at %zu\n&quot;,<br>           offsetof(struct inner, a), offsetof(struct inner, b));</pre><pre>    printf(&quot;sizeof(struct outer) = %zu\n&quot;, sizeof(struct outer));<br>    printf(&quot;flag at %zu, nest at %zu, id at %zu\n&quot;,<br>           offsetof(struct outer, flag),<br>           offsetof(struct outer, nest),<br>           offsetof(struct outer, id));<br>    return 0;<br>}</pre><p>Output:</p><pre>sizeof(struct inner) = 8<br>a at 0, b at 4<br>sizeof(struct outer) = 16<br>flag at 0, nest at 4, id at 12</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3s2AdRgxUKLnZYJ.png" /></figure><p>struct inner is the familiar case from the last post. a takes byte 0. b is an int, so it starts at 4, and bytes 1 to 3 are a hole. The inner struct is 8 bytes and has an alignment of 4.</p><p>In struct outer, flag takes byte 0. nest cannot start at 1, because the inner struct needs a multiple of 4. So nest starts at 4, and bytes 1 to 3 are padding in the outer struct. The 8 bytes of nest occupy 4 to 11, including the hole inside inner. id starts at 12. The outer struct is 16 bytes.</p><p>So there are two layers of padding. One hole lives inside nest, so that b is aligned. One hole lives in the outer struct, so that nest itself is aligned. If you only add up flag (1), a (1), b (4) and id (4), you get 10. sizeof says 16. The extra 6 bytes are those two holes.</p><h3>How do you reach a nested field?</h3><p>With a struct variable, you use a dot for the outer field and another dot for the inner one, like s1.addr.pin. With a pointer to the outer struct, you use the arrow operator to reach the inner struct, then a dot for its field, like p-&gt;addr.pin. You can also take the address of the inner struct and use the arrow operator on that.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;</pre><pre>struct address {<br>    char city[20];<br>    int  pin;<br>};</pre><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>    struct address addr;<br>};</pre><pre>int main(void)<br>{<br>    struct student s1;<br>    struct student *p;<br>    struct address *ap;</pre><pre>    s1.roll_no = 1;<br>    strcpy(s1.name, &quot;Asha&quot;);<br>    s1.marks = 88.5f;<br>    strcpy(s1.addr.city, &quot;Pune&quot;);<br>    s1.addr.pin = 411001;</pre><pre>    printf(&quot;s1.addr.city = %s\n&quot;, s1.addr.city);<br>    printf(&quot;s1.addr.pin  = %d\n&quot;, s1.addr.pin);</pre><pre>    p = &amp;s1;<br>    printf(&quot;p-&gt;addr.city = %s\n&quot;, p-&gt;addr.city);<br>    printf(&quot;p-&gt;addr.pin  = %d\n&quot;, p-&gt;addr.pin);</pre><pre>    ap = &amp;s1.addr;<br>    printf(&quot;ap-&gt;city = %s\n&quot;, ap-&gt;city);<br>    printf(&quot;ap-&gt;pin  = %d\n&quot;, ap-&gt;pin);</pre><pre>    return 0;<br>}</pre><p>Output:</p><pre>s1.addr.city = Pune<br>s1.addr.pin  = 411001<br>p-&gt;addr.city = Pune<br>p-&gt;addr.pin  = 411001<br>ap-&gt;city = Pune<br>ap-&gt;pin  = 411001</pre><p>All three paths reach the same fields. ap is a pointer to the inner struct only. It does not know about roll_no or marks. The next section is about the other direction: starting from an inner pointer like ap and finding the outer student again.</p><p>The next post in this series will spend more time on pointers to structs. For this post, it is enough to know that p-&gt;addr is the same as (*p).addr, and that &amp;s1.addr is the address of the inner block inside s1.</p><h3>Copying and initialising a nested struct</h3><p>You can fill a nested struct with a designated initialiser, using the field names. You can also copy the inner struct in one assignment. That copy is a copy of the bytes, not a shared object.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;</pre><pre>struct address {<br>    char city[20];<br>    int  pin;<br>};</pre><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>    struct address addr;<br>};</pre><pre>int main(void)<br>{<br>    struct student s1 = {<br>        .roll_no = 1,<br>        .name    = &quot;Asha&quot;,<br>        .marks   = 88.5f,<br>        .addr    = {<br>            .city = &quot;Pune&quot;,<br>            .pin  = 411001,<br>        },<br>    };</pre><pre>    struct student s2;<br>    struct address home = { .city = &quot;Nashik&quot;, .pin = 422001 };</pre><pre>    memset(&amp;s2, 0, sizeof s2);<br>    s2.roll_no = 2;<br>    strcpy(s2.name, &quot;Rohan&quot;);<br>    s2.marks = 76.0f;<br>    s2.addr  = home;</pre><pre>    printf(&quot;s1: %s, %s, %d\n&quot;, s1.name, s1.addr.city, s1.addr.pin);<br>    printf(&quot;s2: %s, %s, %d\n&quot;, s2.name, s2.addr.city, s2.addr.pin);</pre><pre>    home.pin = 0;<br>    printf(&quot;after home.pin = 0, s2.addr.pin is still %d\n&quot;, s2.addr.pin);<br>    return 0;<br>}</pre><p>Output:</p><pre>s1: Asha, Pune, 411001<br>s2: Rohan, Nashik, 422001<br>after home.pin = 0, s2.addr.pin is still 422001</pre><p>The .addr = { .city = &quot;Pune&quot;, .pin = 411001 } part fills the inner struct by name. Any field you leave out is set to zero.</p><p>s2.addr = home copies all 24 bytes of home into s2. Changing home afterwards does not change s2. The two structs are separate.</p><p>You can also assign one whole student to another, s2 = s1, and the nested address is copied with it.</p><h3>Read the rest on Jupius</h3><p>That covers how to nest one struct in another, how the inner block is padded, and how to fill or copy a nested struct. The second half of the post moves into the Linux kernel. It shows how thread_struct sits inside task_struct, and how container_of takes an embedded list_head and gives you back the outer struct.</p><p><a href="https://www.jupiuslearning.com/blog/c-structs-inside-structs-nesting-container-of-linux-kernel/">Read the full post on Jupius Learning</a>. It is free, with every example, the diagrams and the practice exercises.</p><p>If you want to practice structs with small exercises that check your code as you go, the <a href="https://www.jupiuslearning.com/courses/c-prog-a/">C programming course</a> at Jupius Learning covers them step by step.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f0d4567976b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First Zephyr App on the ESP32-S3: Blink an LED with Devicetree and GPIO]]></title>
            <link>https://medium.com/@vadhernknj19/your-first-zephyr-app-on-the-esp32-s3-blink-an-led-with-devicetree-and-gpio-163ee6a133b4?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/163ee6a133b4</guid>
            <category><![CDATA[zephyr]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[tor]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 07:23:49 GMT</pubDate>
            <atom:updated>2026-11-27T07:23:49.056Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post was first published on </em><a href="https://www.jupiuslearning.com/blog/your-first-zephyr-app-esp32-s3-blink-led-devicetree-gpio/"><em>Jupius Learning</em></a><em>, where you can read it free with diagrams and practice exercises.</em></p><p><a href="https://www.jupiuslearning.com/blog/#subscribe"><em>Subscribe to our articles for regular updates</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H9Legab5KQ0o8ATF.png" /></figure><p>In the <a href="https://www.jupiuslearning.com/blog/zephyr-rtos-explained-a-simple-start-on-the-esp32-s3/">first Zephyr post</a> we looked at what an RTOS is, and we wrote a small program where two threads talk through a message queue. The <a href="https://www.jupiuslearning.com/blog/learning-zephyr-rtos-on-real-hardware-how-our-24-week-course-works/">second post</a> showed how our 24 week course is laid out on a real ESP32-S3 board.</p><p>This time we write a first app that talks to a pin. The pin comes from a Devicetree overlay, not from a number written in the C file. Then we flash the app and watch the printk lines as the LED blinks.</p><h3>What you need</h3><p>You need a Zephyr workspace with west already working. The official <a href="https://docs.zephyrproject.org/latest/develop/getting_started/index.html">Getting Started Guide</a> covers the source checkout and the Zephyr SDK. On Windows, use PowerShell. Create the virtual environment with py -3.12 -m venv zephyrproject\.venv, then activate it with .\zephyrproject\.venv\Scripts\Activate.ps1. Activate that environment every time you open a new terminal, or west will not be found.</p><p>You also need an ESP32-S3-DevKitC board. The course uses the ESP32-S3-DevKitC-1. In current Zephyr docs the board name is esp32s3_devkitc. Because the chip has two cores, the build target you should pass to west is esp32s3_devkitc/esp32s3/procpu. That selects the ESP32-S3 SoC and the PROCPU, which is the core that can use printk and the console UART.</p><p>Plug the USB cable into the port labelled UART, not the one labelled USB. The DevKitC-1 has both. west flash and the serial monitor use the UART port.</p><p>For the LED itself, use an external one. You will also need a resistor around 220 ohm and two jumper wires.</p><p>This matters because many ESP32-S3-DevKitC boards do not have a plain on-board GPIO LED. They have an addressable RGB LED instead. On the first board revision that LED is on GPIO 48. On v1.1 it is on GPIO 38. A simple GPIO toggle will not blink it the way Zephyr’s Blinky sample expects. The official esp32s3_devkitc board file also has no led0 alias. The 3.3 V power LED on the board is only a power indicator. You cannot drive it from your code.</p><p>So we wire an external LED to a GPIO and describe that pin in an overlay.</p><h3>Create the app folder</h3><p>Put the app inside your Zephyr workspace, for example zephyrproject/app/blink_led. Current Zephyr docs use this layout:</p><pre>blink_led/<br>├── CMakeLists.txt<br>├── app.overlay<br>├── prj.conf<br>└── src<br>    └── main.c</pre><p>In PowerShell:</p><pre>cd $Env:HOMEPATH\zephyrproject<br>mkdir app\blink_led\src</pre><p>On Linux or macOS, the same idea is mkdir -p ~/zephyrproject/app/blink_led/src.</p><p>CMakeLists.txt is the entry point for the build. This matches the current Application Development docs, which use CMake 3.20 or newer. The docs now show 3.28.0 in the example. 3.20.0 still works on Zephyr 4.1, which is what our course uses. If a newer Zephyr release complains, change the first line to 3.28.0.</p><pre>cmake_minimum_required(VERSION 3.20.0)</pre><pre>find_package(Zephyr)<br>project(blink_led)</pre><pre>target_sources(app PRIVATE src/main.c)</pre><p>find_package(Zephyr) must come before project(). It creates a CMake target named app. Your source file is added to that target.</p><p>prj.conf turns on the GPIO driver:</p><pre>CONFIG_GPIO=y</pre><p>The board file already turns on UART0 as the console, and printk is on by default. You do not need extra console options for this app.</p><h3>How the board Devicetree describes hardware</h3><p>In the first post I said Zephyr keeps pin details out of your C code. Those details live in a Devicetree. The official board file for the ESP32-S3-DevKitC already describes UART0 and the GPIO controllers. It also describes the BOOT button, which has the alias sw0 on GPIO 0. There is no LED alias.</p><p>On this SoC there are two GPIO controllers. gpio0 covers pins 0 to 31. gpio1 covers pins 32 to 53. We will use GPIO 4, which sits on gpio0, so the Devicetree writes it as &amp;gpio0 4.</p><p>GPIO 4 is a safe choice on this board. Leave GPIO 0 alone, because that is the BOOT button. Leave GPIO 19 and 20 alone, because those are used by USB. Leave GPIO 43 and 44 alone, because those are the console UART. Also avoid the flash and PSRAM pins on your module, which are often in the mid thirties on ESP32-S3-WROOM parts.</p><h3>Add an led0 alias with an overlay</h3><p>An overlay is a small Devicetree file that is merged with the board file at build time. Zephyr looks for app.overlay in your app folder automatically, so you do not have to pass a special flag.</p><p>Create app.overlay with this content:</p><pre>/ {<br>    aliases {<br>        led0 = &amp;ext_led;<br>    };</pre><pre>    leds {<br>        compatible = &quot;gpio-leds&quot;;<br>        ext_led: led_0 {<br>            gpios = &lt;&amp;gpio0 4 GPIO_ACTIVE_HIGH&gt;;<br>        };<br>    };<br>};</pre><p>The led0 alias points at a node named ext_led. That node says the LED is on gpio0, pin 4, and that it turns on when the pin goes high. GPIO_ACTIVE_HIGH matches the usual wiring: GPIO 4 to the resistor, then to the LED&#39;s longer leg (the anode). The shorter leg goes to GND.</p><p>If you later move the LED to another pin, you change only this overlay. The C code still asks for led0 by name.</p><h3>The GPIO API in main.c</h3><p>Put this in src/main.c:</p><pre>#include &lt;zephyr/kernel.h&gt;<br>#include &lt;zephyr/drivers/gpio.h&gt;<br>#include &lt;zephyr/sys/printk.h&gt;</pre><pre>#define SLEEP_TIME_MS 1000<br>#define LED0_NODE DT_ALIAS(led0)</pre><pre>static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);</pre><pre>int main(void)<br>{<br>    int ret;<br>    bool on = true;</pre><pre>    if (!gpio_is_ready_dt(&amp;led)) {<br>        printk(&quot;LED GPIO is not ready\n&quot;);<br>        return 0;<br>    }</pre><pre>    ret = gpio_pin_configure_dt(&amp;led, GPIO_OUTPUT_ACTIVE);<br>    if (ret &lt; 0) {<br>        printk(&quot;Failed to configure the LED pin\n&quot;);<br>        return 0;<br>    }</pre><pre>    printk(&quot;LED on\n&quot;);</pre><pre>    while (1) {<br>        k_msleep(SLEEP_TIME_MS);</pre><pre>        ret = gpio_pin_toggle_dt(&amp;led);<br>        if (ret &lt; 0) {<br>            printk(&quot;Failed to toggle the LED pin\n&quot;);<br>            return 0;<br>        }</pre><pre>        on = !on;<br>        printk(&quot;LED %s\n&quot;, on ? &quot;on&quot; : &quot;off&quot;);<br>    }</pre><pre>    return 0;<br>}</pre><p>DT_ALIAS(led0) is the Devicetree node for the led0 alias. GPIO_DT_SPEC_GET reads the gpios property of that node and fills a struct gpio_dt_spec. That struct holds the GPIO port and the pin number, plus the flags from the overlay. If the alias is missing, this line fails at build time, often with a long error that mentions DT_N_ALIAS_led.</p><p>gpio_is_ready_dt checks that the GPIO port is ready before you use it. gpio_pin_configure_dt sets the pin as an output. GPIO_OUTPUT_ACTIVE means the pin starts at its active level, so with GPIO_ACTIVE_HIGH the LED is on when main begins.</p><p>gpio_pin_toggle_dt flips the pin each time around the loop. k_msleep(1000) waits one second and gives the CPU to any other thread that is ready. That is the same sleep we used in the first post, and it is not like Arduino&#39;s delay(), which blocks everything.</p><p>A build error on the GPIO_DT_SPEC_GET line almost always means the overlay was not picked up, or the alias name does not match.</p><h3>Read the rest on Jupius</h3><p>That covers the app folder and the led0 overlay, plus the C code that blinks the pin. The second half of the post is the practical part: the west commands to build and flash, how to read the printk lines with west espressif monitor, the mistakes that usually show up on this board, and a few exercises.</p><p><a href="https://www.jupiuslearning.com/blog/your-first-zephyr-app-esp32-s3-blink-led-devicetree-gpio/">Read the full post on Jupius Learning</a>. It is free, with the wiring diagram and the practice exercises.</p><p>If you want to go further on a real ESP32-S3 board, the <a href="https://www.jupiuslearning.com/courses/zep-rtos-a/">Zephyr RTOS on ESP32-S3</a> course at Jupius Learning starts with this setup and then moves on to kernel objects, Devicetree and GPIO.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163ee6a133b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a C Struct Sits in Memory: Size, Padding and Alignment (Linux Kernel Examples)]]></title>
            <link>https://medium.com/@vadhernknj19/how-a-c-struct-sits-in-memory-size-padding-and-alignment-linux-kernel-examples-12ca51cfb354?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ca51cfb354</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 08:23:30 GMT</pubDate>
            <atom:updated>2026-11-24T08:23:30.706Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post is partial and was first published on </em><a href="https://www.jupiuslearning.com/blog/c-struct-padding-alignment-memory-linux-kernel/"><em>Jupius Learning</em></a><em>, where you can read it free with diagrams and practice exercises.</em></p><p><a href="https://www.jupiuslearning.com/blog/#subscribe"><em>Subscribe to our articles for regular updates</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xZlTjUfWspHcK4L3.png" /></figure><p>A C struct is often bigger than the sum of its fields. The compiler puts each field at an address that suits its type, and to do that it sometimes leaves empty bytes between fields, or at the end. Those empty bytes are called padding. The rule that decides where a field may start is called alignment.</p><p>In the <a href="https://www.jupiuslearning.com/blog/your-first-c-struct-declare-fill-read-linux-kernel/">first post of this series</a> we declared a struct student, filled it and read it. In the <a href="https://www.jupiuslearning.com/blog/typedef-struct-short-name-linux-kernel/">last post</a> we gave it a short name with typedef. This time we look at how that struct is laid out in memory, and how the Linux kernel controls the layout of its own structs.</p><p>All the sizes in this post come from gcc on a 64-bit x86 Linux machine. I compiled and ran every program shown here. On a different CPU or compiler a few numbers may change, and I will point out where.</p><h3>Why is sizeof a struct bigger than its fields?</h3><p>Here is the student struct again. This time we print its size and where each field starts.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stddef.h&gt;</pre><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>};</pre><pre>int main(void)<br>{<br>    printf(&quot;sizeof(int)   = %zu\n&quot;, sizeof(int));<br>    printf(&quot;sizeof(float) = %zu\n&quot;, sizeof(float));<br>    printf(&quot;sizeof(struct student) = %zu\n&quot;, sizeof(struct student));</pre><pre>    printf(&quot;roll_no at offset %zu\n&quot;, offsetof(struct student, roll_no));<br>    printf(&quot;name    at offset %zu\n&quot;, offsetof(struct student, name));<br>    printf(&quot;marks   at offset %zu\n&quot;, offsetof(struct student, marks));</pre><pre>    return 0;<br>}</pre><p>Save it as student_size.c, then compile and run it:</p><pre>gcc student_size.c -o student_size<br>./student_size</pre><p>In PowerShell with MinGW, run it with .\student_size.exe.</p><p>Output:</p><pre>sizeof(int)   = 4<br>sizeof(float) = 4<br>sizeof(struct student) = 60<br>roll_no at offset 0<br>name    at offset 4<br>marks   at offset 56</pre><p>The fields add up to 4 + 50 + 4 = 58 bytes. sizeof says 60.</p><p>roll_no starts at byte 0 and takes 4 bytes. name starts at byte 4 and takes 50 bytes, so it ends at byte 53. The next free byte is 54, but marks starts at 56. Bytes 54 and 55 are padding. Nobody uses them. They are there so that marks starts at a multiple of 4.</p><p>offsetof is a macro from &lt;stddef.h&gt;. It tells you how many bytes from the start of the struct a field begins. It is the simplest way to see padding for yourself.</p><h3>What is alignment in C?</h3><p>Most types have an alignment. It is the number that the field’s address must be a multiple of. On x86–64 Linux with gcc, the common ones look like this:</p><pre>Type                          Size  Alignment<br>char                          1     1<br>short                         2     2<br>int, float                    4     4<br>long, double, any pointer     8     8</pre><p>A char can go anywhere. An int must start at an address that is a multiple of 4. A pointer must start at a multiple of 8.</p><p>The reason is the hardware. A CPU reads memory in chunks, and a value that sits neatly inside one chunk is quick to load. On x86 a misaligned read still works, it is just slower in some cases. On some other CPUs a misaligned read can trap. So C compilers follow the alignment rules of the platform, and they add padding to make the rules hold.</p><p>The compiler follows two simple rules for a struct:</p><ul><li>Each field starts at the next offset that is a multiple of its own alignment.</li><li>The whole struct gets the alignment of its strictest field, and its size is rounded up to a multiple of that.</li></ul><p>The second rule is why padding can appear at the end. If you make an array of structs, every element must start at a properly aligned address too, not only the first one.</p><p>Our student struct has int and float fields, so its alignment is 4. 58 is not a multiple of 4, so the struct is 60 bytes. In this case the padding happens to sit before marks, and no extra bytes are needed at the end.</p><h3>How field order changes the size of a C struct</h3><p>Here are two structs with the same three fields in a different order.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stddef.h&gt;</pre><pre>struct bad {<br>    char a;<br>    int  b;<br>    char c;<br>};</pre><pre>struct good {<br>    int  b;<br>    char a;<br>    char c;<br>};</pre><pre>int main(void)<br>{<br>    struct bad  x = { 0 };<br>    struct good y = { 0 };</pre><pre>    printf(&quot;struct bad:  size %zu, a at %zu, b at %zu, c at %zu\n&quot;,<br>           sizeof x, offsetof(struct bad, a),<br>           offsetof(struct bad, b), offsetof(struct bad, c));<br>    printf(&quot;struct good: size %zu, b at %zu, a at %zu, c at %zu\n&quot;,<br>           sizeof y, offsetof(struct good, b),<br>           offsetof(struct good, a), offsetof(struct good, c));<br>    return 0;<br>}</pre><p>Output:</p><pre>struct bad:  size 12, a at 0, b at 4, c at 8<br>struct good: size 8, b at 0, a at 4, c at 5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zgra8Q0mwmlAuIj5.png" /></figure><p>In struct bad, a takes byte 0. b is an int, so it can&#39;t start at 1. It goes to 4, and bytes 1 to 3 are a hole. c sits at byte 8. The struct needs a size that is a multiple of 4, so bytes 9 to 11 are padding at the end. That is 6 bytes of data in a 12 byte struct.</p><p>In struct good, b goes first at byte 0. The two char fields fit right after it at 4 and 5. Two bytes of padding at the end round the size up to 8.</p><p>Nothing about the data changed. Only the order did, and the struct shrank by a third.</p><p>The gap grows when pointers are involved, because a pointer needs 8 byte alignment on a 64-bit machine:</p><pre>#include &lt;stdio.h&gt;</pre><pre>struct item_bad {<br>    char  flag;<br>    void *data;<br>    char  kind;<br>};</pre><pre>struct item_good {<br>    void *data;<br>    char  flag;<br>    char  kind;<br>};</pre><pre>int main(void)<br>{<br>    printf(&quot;item_bad:  %zu bytes\n&quot;, sizeof(struct item_bad));<br>    printf(&quot;item_good: %zu bytes\n&quot;, sizeof(struct item_good));<br>    printf(&quot;1000 of item_bad:  %zu bytes\n&quot;, 1000 * sizeof(struct item_bad));<br>    printf(&quot;1000 of item_good: %zu bytes\n&quot;, 1000 * sizeof(struct item_good));<br>    return 0;<br>}</pre><p>Output:</p><pre>item_bad:  24 bytes<br>item_good: 16 bytes<br>1000 of item_bad:  24000 bytes<br>1000 of item_good: 16000 bytes</pre><p>For one struct, 8 bytes does not matter. For a thousand of them it is 8000 bytes. The Linux kernel keeps millions of some structs in memory at once, one for every page of RAM or every open file. That is why kernel developers care about the order of fields.</p><p>A simple habit works most of the time: put the biggest fields first, pointers and long values, then int, then short, then char. Related fields often still belong together for readability, so it is a habit, not a law.</p><h3>See the holes with pahole</h3><p>Counting offsets by hand gets tiring. The pahole tool reads the debug information in a compiled program and prints every struct with its holes marked. It comes in the dwarves package on Debian and Ubuntu (sudo apt install dwarves).</p><p>Compile the order example with -g so the debug information is there, then ask pahole about struct bad:</p><pre>gcc -g order.c -o order<br>pahole -C bad order</pre><p>Output:</p><pre>struct bad {<br>    char                       a;                    /*     0     1 */</pre><pre>    /* XXX 3 bytes hole, try to pack */</pre><pre>    int                        b;                    /*     4     4 */<br>    char                       c;                    /*     8     1 */</pre><pre>    /* size: 12, cachelines: 1, members: 3 */<br>    /* sum members: 6, holes: 1, sum holes: 3 */<br>    /* padding: 3 */<br>    /* last cacheline: 12 bytes */<br>};</pre><p>The two numbers on each line are the offset and the size. pahole finds the 3 byte hole after a and the 3 bytes of padding at the end, and it even suggests you try to pack the struct. On my machine pahole also printed a short warning line about a missing BTF section. You can ignore that for a normal user program.</p><p>The same tool works on the Linux kernel itself. If you have a vmlinux with debug information, pahole -C task_struct vmlinux prints the full layout of the process descriptor. We walked through its fields in <a href="https://www.jupiuslearning.com/blog/task-struct-linux-kernel-every-field-explained/">task_struct in the Linux Kernel: Every Field Explained</a>. Kernel developers use pahole in exactly this way to find holes in busy structs and move fields around to close them.</p><h3>Read the rest on Jupius</h3><p>That covers how the compiler pads a struct and how to see the holes. The second half of the post moves into the Linux kernel. It shows how ext2_group_desc names its own padding with bg_pad, why the ext2 superblock ends in 760 bytes of reserved space, how BUILD_BUG_ON stops the kernel build when a struct grows too big, and when the kernel uses __attribute__((packed)) and cache line alignment.</p><p><a href="https://www.jupiuslearning.com/blog/c-struct-padding-alignment-memory-linux-kernel/">Read the full post on Jupius Learning</a>. It is free, with every example and the diagrams.</p><p>If you want to practice structs with small exercises that check your code as you go, the <a href="https://www.jupiuslearning.com/courses/c-prog-a/">C programming course</a> at Jupius Learning covers them step by step.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ca51cfb354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[typedef struct: Giving Your Struct a Short Name (Linux Kernel Examples)]]></title>
            <link>https://medium.com/@vadhernknj19/typedef-struct-giving-your-struct-a-short-name-linux-kernel-examples-788d1cf28c56?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/788d1cf28c56</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 13:27:37 GMT</pubDate>
            <atom:updated>2026-11-19T13:27:37.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uinBEYUCv3stJb-x.jpg" /></figure><p><em>This post was first published on </em><a href="https://www.jupiuslearning.com/blog/typedef-struct-short-name-linux-kernel/"><em>Jupius Learning</em></a><em>, where you can read it free with diagrams and practice exercises.</em></p><p>typedef gives an existing type a second name. When you write typedef struct student student_t, you can make a variable with student_t s1 instead of struct student s1. Nothing about the data changes. The typedef does not create a new kind of object, and it does not set aside any memory. It is only another name for a type you already have.</p><p>In the <a href="https://www.jupiuslearning.com/blog/your-first-c-struct-declare-fill-read-linux-kernel/">last post</a> we declared a struct student, filled it and read it with a dot. You probably noticed that writing struct student every time is a bit long. This post is about that shorter name, and about why the Linux kernel uses typedef for some types and avoids it for most.</p><h3>What does typedef do to a C struct?</h3><p>Start with the struct from last time, then give it a typedef name.</p><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>};</pre><pre>typedef struct student student_t;</pre><p>You can also write both in one go:</p><pre>typedef struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>} student_t;</pre><p>After either of those, these two lines make the same kind of variable:</p><pre>struct student s1 = { 1, &quot;Asha&quot;, 87.5f };<br>student_t      s2 = { 2, &quot;Ravi&quot;, 91.0f };</pre><p>struct student is still a valid type name. The word student after struct is the tag. student_t is the typedef name. They describe the same layout. s1.marks and s2.marks work the same way, with the same dot we used last time.</p><p>The _t at the end is only a naming habit. It is common in C, but it is not required. I will stick to student_t here because you will see that pattern a lot.</p><h3>typedef with an anonymous struct</h3><p>You do not have to give the struct a tag at all. If you leave the tag out, the typedef name is the only name the type has.</p><pre>typedef struct {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>} student_t;</pre><p>Now student_t s1; works, and struct student s1; does not, because there is no tag called student. The struct is anonymous. This is shorter to type. The cost is that the type has only one name, which matters as soon as you need to mention the type before it is fully defined.</p><p>The Linux kernel uses this shape for sigset_t, a signal mask. In a modern kernel it looks like this, in simplified form:</p><pre>/* Simplified from the Linux kernel */<br>typedef struct {<br>    unsigned long sig[_NSIG_WORDS];<br>} sigset_t;</pre><p>_NSIG_WORDS is a kernel macro for how many unsigned long values it takes to hold every signal bit. On an older 32-bit kernel you may see sig[2], which is the same idea with the number filled in. You treat sigset_t as its own type, and you usually change it through helper functions rather than writing to the sig field yourself.</p><h3>The forward-declaration case</h3><p>Sometimes you need to mention a struct type before you have written its fields. A function prototype is a common reason. A field that points to the same type of struct is another. In C you can give the compiler the typedef name early, as long as the struct has a tag.</p><pre>typedef struct student student_t;   /* the typedef comes first */</pre><pre>void print_student(const student_t *s);</pre><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>    student_t *partner;            /* a pointer is fine here */<br>};</pre><p>The typedef line does not describe the fields yet. It only says there is a struct student, and student_t is another name for it. A pointer to an incomplete type is allowed, so the prototype and the partner field both compile. You cannot make a student_t variable until the braces that list the fields have been seen.</p><p>If you try to put the typedef name inside the same typedef that creates it, that does not work:</p><pre>typedef struct student {<br>    int roll_no;<br>    /* student_t *partner; */    /* too early: student_t does not exist yet */<br>    struct student *partner;     /* this is fine: the tag already exists */<br>} student_t;</pre><p>The tag student is visible from the opening brace. The typedef name student_t exists only after the semicolon that finishes the typedef.</p><p>An anonymous typedef cannot be written this way. There is no tag to mention in a forward line, so you cannot say the type exists and fill in the fields later. If you think you will need a forward declaration, keep the tag.</p><p>The -&gt; in a function like print_student is the arrow I mentioned last time. You use it when you have a pointer to a struct. We will spend a later post on pointers. For the rest of this post, the examples in main still use a plain variable and a dot.</p><h3>A typedef that hides a pointer</h3><p>typedef can name a pointer type too:</p><pre>typedef struct student *student_ptr;</pre><pre>student_ptr p;</pre><p>p is a pointer, but the name does not show that. student_ptr p; looks a lot like student_t s;, which is a struct variable, not a pointer. If you later write p.marks, the compiler will complain, because a pointer needs p-&gt;marks. That mix-up is easy to miss when you read someone else&#39;s code.</p><p>This is the main reason the Linux kernel coding style says not to typedef ordinary structs or pointers. When you see a line like vps_t a;, you cannot tell if a is a struct or a pointer. It could even be an integer. When you see struct virtual_container *a;, you can. I will come back to that rule after we look at the typedefs the kernel does keep.</p><h3>A complete C example you can run</h3><p>Here is the named typedef, used the same way we used struct student in the last post.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;</pre><pre>typedef struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>} student_t;</pre><pre>int main(void)<br>{<br>    struct student s1 = { 1, &quot;Asha&quot;, 87.5f };</pre><pre>    student_t s2 = { 0 };<br>    s2.roll_no = 2;<br>    strcpy(s2.name, &quot;Ravi&quot;);<br>    s2.marks = 91.0f;</pre><pre>    printf(&quot;%d %s %.1f\n&quot;, s1.roll_no, s1.name, s1.marks);<br>    printf(&quot;%d %s %.1f\n&quot;, s2.roll_no, s2.name, s2.marks);</pre><pre>    return 0;<br>}</pre><p>Save it as student_t.c, then compile and run it:</p><pre>gcc student_t.c -o student_t<br>./student_t</pre><p>On Windows with MinGW installed, the second line in PowerShell is .\student_t.exe.</p><p>Output:</p><pre>1 Asha 87.5<br>2 Ravi 91.0</pre><p>s1 uses the tag name. s2 uses the typedef name. Both are the same type, so the rest of the program does not care which spelling you picked.</p><h3>typedef in the Linux kernel: wait_queue_head_t</h3><p>The Linux kernel does use typedef on some structs, including a few older names that are still around. One you will meet often is wait_queue_head_t. A wait queue head is the handle kernel code uses when a task needs to sleep until something happens. Here is the typedef, simplified from a current kernel:</p><pre>/* Simplified from the Linux kernel */<br>struct wait_queue_head {<br>    spinlock_t        lock;<br>    struct list_head  head;<br>};<br>typedef struct wait_queue_head wait_queue_head_t;</pre><p>That is the same pattern as typedef struct student student_t. The struct keeps a tag, wait_queue_head, and the typedef gives it a short name. In older kernels the tag was __wait_queue_head, and the typedef name was already wait_queue_head_t.</p><p>The item on the queue used to have its own typedef, wait_queue_t. Today that struct is struct wait_queue_entry, and the typedef is wait_queue_entry_t. If you read older kernel material and see wait_queue_t, that is the old name.</p><p>Notice spinlock_t in the first field. That is another typedef. I will come back to it in a moment. The head field links waiting tasks together. Lists get their own series later, so we will not unpack that here.</p><p>Even here, a lot of current kernel code says struct wait_queue_head rather than wait_queue_head_t. The typedef still exists so older code keeps compiling.</p><h3>Why the Linux kernel typedefs pte_t and pgd_t</h3><p>Some typedefs in the Linux kernel are not there to save typing. They exist so the compiler will stop you mixing up two values that happen to hold the same kind of number.</p><p>The kernel’s page tables are a good example. On a typical x86–64 machine, a page table entry and a page global directory entry are both an unsigned long underneath. If they used the same type, you could assign one to the other and the compiler would stay quiet. They are not the same thing, so that assignment should be a mistake.</p><p>The kernel wraps each one in its own struct, then typedefs that struct. This is a shortened form of the x86–64 definitions:</p><pre>/* Simplified from the Linux kernel, x86-64 */<br>typedef struct { unsigned long pte; } pte_t;<br>typedef struct { unsigned long pgd; } pgd_t;</pre><p>pte_t and pgd_t each hold one number, but they are different types. C will not let you assign a pte_t to a pgd_t. The kernel coding style calls types like these opaque. Ordinary code is not supposed to read the field by name. It uses helper functions such as pte_val() and __pte(), or pgd_val() and __pgd(), so you cannot mix them up by accident.</p><p>You can see the type check with a tiny program. It prints the two values, and it leaves one bad assignment commented out.</p><pre>#include &lt;stdio.h&gt;</pre><pre>/* Same idea as the kernel&#39;s wrapper typedefs */<br>typedef struct { unsigned long pte; } pte_t;<br>typedef struct { unsigned long pgd; } pgd_t;</pre><pre>int main(void)<br>{<br>    pte_t e = { 0xabc };<br>    pgd_t d = { 0x1000 };</pre><pre>    printf(&quot;pte=0x%lx pgd=0x%lx\n&quot;, e.pte, d.pgd);</pre><pre>    /* d = e; */<br>    /* If you uncomment that line, gcc says:<br>       incompatible types when assigning to type &#39;pgd_t&#39; from type &#39;pte_t&#39; */</pre><pre>    return 0;<br>}</pre><p>Save it as pte_pgd.c, compile it with gcc pte_pgd.c -o pte_pgd, and run ./pte_pgd. In PowerShell the run command is .\pte_pgd.exe.</p><p>Output:</p><pre>pte=0xabc pgd=0x1000</pre><p>I am reading e.pte and d.pgd here only to print them. In real Linux kernel code you would go through the helpers, so most files never mention the field name at all. If those two types had been a plain unsigned long, the assignment d = e would have compiled, and a bug like that could have been hard to spot.</p><h3>atomic_t and spinlock_t in the Linux kernel</h3><p>atomic_t and spinlock_t are two more typedefs you will keep seeing in Linux kernel structs. Both are there so that callers use the official helper functions, rather than touching the inside of the type directly.</p><p>atomic_t is a counter that the kernel can update without being interrupted halfway through. A simplified form of the current typedef is:</p><pre>/* Simplified from the Linux kernel */<br>typedef struct {<br>    int counter;<br>} atomic_t;</pre><p>It looks like a struct with one int in it. The point of the typedef is that kernel code should not write v.counter++. A C ++ is not guaranteed to be atomic, so the kernel gives you helpers such as atomic_read(), atomic_set() and atomic_inc(). Those are implemented as single atomic instructions. Ordinary code is meant to go through the helpers, not treat the counter as a plain int.</p><p>spinlock_t is a typedef for struct spinlock:</p><pre>/* Simplified from the Linux kernel */<br>typedef struct spinlock spinlock_t;</pre><p>A spin lock is how one CPU holds a short lock while another CPU waits. The inside of struct spinlock changes with kernel config options, so most code never mentions the fields. It uses helpers such as spin_lock() and spin_unlock(). In older kernels you may see field names such as slock. Today you should treat spinlock_t as a type you pass to the helpers, not as a struct you fill in by hand.</p><h3>Why the Linux kernel mostly avoids typedef</h3><p>If typedef is so handy, why does the Linux kernel not use it on task_struct, timespec and most of the other structs in this series?</p><p>The <a href="https://www.kernel.org/doc/html/latest/process/coding-style.html#typedefs">Linux kernel coding style</a> is direct about this. It says it is a mistake to typedef ordinary structures and pointers. The example in the document is the one I used earlier. vps_t a; hides what a is. struct virtual_container *a; does not. The rule of thumb is: a pointer, or a struct whose fields can reasonably be accessed directly, should never be a typedef.</p><p>That is why you write struct task_struct * in kernel code, not task_t or task_ptr. You can see it is a struct, and you can see it is a pointer. The same goes for struct timespec from the last post.</p><p>The same document says typedefs are allowed when they fall into a few special cases. The ones that matter for structs are these.</p><p>Opaque types, such as pte_t. You are not supposed to look inside. You only use the accessor functions. The coding style mentions pte_t by name as the example.</p><p>Wrapper types that exist so the compiler can type-check two values that would otherwise look the same. pte_t and pgd_t are this idea in struct form. The kernel also uses a tool called sparse, which can turn an integer typedef into a distinct type for checking.</p><p>Fixed-size integers, such as u32. These are typedefs for integers of a known width, so you are not left wondering whether a value is an int or a long. The coding style also allows the __u32 form in headers that userspace may include, because those headers cannot always use the C99 names or the kernel&#39;s u32.</p><p>The document is strict about the closing rule: do not add a typedef unless you can clearly match one of those cases. Older kernel code does not always follow today’s rule. wait_queue_head_t is a leftover of that kind. Its fields are meant to be used, and current code often writes struct wait_queue_head instead. For new kernel code, and for your own structs as you learn, the safer default is the one we used in the last post: keep the struct tag visible, and add a typedef only when you have a reason like the ones above.</p><p>In your own user programs, typedef struct student student_t is still fine. Plenty of good C code does it. Just be careful not to typedef a pointer, and remember that the typedef is only a name. When you start reading Linux kernel sources, expect struct to be spelled out most of the time.</p><h3>What comes next</h3><p>We now have two ways to name a struct type: the struct tag, and a typedef. We also know why Linux kernel typedefs such as pte_t and atomic_t keep those short names, and why struct task_struct does not.</p><p>In the next post, How a Struct Sits in Memory: Size, Padding and Alignment, we will look at what happens when those fields are laid out in memory, and why a struct is sometimes larger than the sum of its fields.</p><p>If you want to practice this with small exercises that check your code as you go, the <a href="https://www.jupiuslearning.com/courses/c-prog-a/">C programming course</a> at Jupius Learning starts from exactly here.</p><h3>Frequently asked questions</h3><h3>What does typedef struct do in C?</h3><p>It gives the struct a second type name. After typedef struct student student_t;, you can write student_t s1; instead of struct student s1;. The typedef does not change the fields, and it does not create a variable on its own.</p><h3>What is the difference between a struct tag and a typedef name?</h3><p>The tag is the word after struct, such as student in struct student. The typedef name, such as student_t, is an alias for that type. You can have both, or you can typedef an anonymous struct and keep only the typedef name. A forward declaration needs the tag.</p><h3>Why can I not use student_t inside its own typedef?</h3><p>Because the typedef name exists only after the finishing semicolon. Inside the braces, the compiler already knows the tag, so you write struct student *partner, not student_t *partner. If you typedef the tag first, on its own line, then student_t * is fine after that.</p><h3>Why does the Linux kernel avoid typedef on most structs?</h3><p>The Linux kernel coding style says a typedef on an ordinary struct or pointer hides what the type is. struct task_struct *p is clear. A name like task_t or task_ptr is not. The kernel keeps typedef for opaque types and for wrappers that help with type checking. It also typedefs fixed-size integers such as u32.</p><h3>Why does the Linux kernel typedef pte_t, atomic_t and spinlock_t?</h3><p>So that each one is a distinct type, and so that most code uses helper functions instead of reading the fields directly. pte_t and pgd_t stop you assigning one kind of page-table value to another. atomic_t and spinlock_t steer you toward helpers such as atomic_inc() and spin_lock().</p><p>Originally published on <a href="https://www.jupiuslearning.com/blog/typedef-struct-short-name-linux-kernel/">Jupius Learning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788d1cf28c56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[task_struct in the Linux Kernel: Every Field Explained]]></title>
            <link>https://medium.com/@vadhernknj19/task-struct-in-the-linux-kernel-every-field-explained-6190a1759899?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6190a1759899</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 08:06:48 GMT</pubDate>
            <atom:updated>2026-11-17T08:06:48.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ujq1nPp1t_B8OXZ1.jpg" /></figure><p>task_struct is the C struct the Linux kernel uses to describe one task. A task is a process or a thread. Every running program on your Linux machine has at least one task_struct, and it holds or points to everything the kernel knows about that task: its state, its IDs, its parent, its memory, its open files, its signals and its scheduling data.</p><p>The struct is defined in include/linux/sched.h. It is also called the process descriptor.</p><p>This post is part of my series on C structs in the Linux kernel. In the <a href="https://www.jupiuslearning.com/blog/the-humble-c-struct-that-still-runs-billions-of-machines/">first post</a> I said the kernel is built out of structs. task_struct is the biggest example of that idea, so it gets a full post of its own.</p><h3>Why is task_struct so big in the Linux kernel?</h3><p>Because it has to answer every question the kernel may ask about a task. Is it running or sleeping? Who started it? Which memory does it use? Which files does it have open? Which signals is it waiting for? How much CPU time has it used?</p><p>In a modern kernel the struct has a few hundred fields. Many of them only exist when a certain config option is turned on, like lockdep, KASAN, NUMA balancing or perf. You do not need all of those to understand a process. So in this post I group the important fields into sections. For each section I show a short, simplified listing first. Then I explain each field: its type, what it means, and the older name if the field had a different name in 2.6 era kernels. Many tutorials and books still show the old names, so it helps to know both.</p><p>The field names here are checked against mainline include/linux/sched.h as of November 2026 (Linux 7.4-rc3). The listings below are trimmed. The real struct has more fields, and they are not in this exact order.</p><h3>How does task_struct connect to other kernel structs?</h3><p>Most of the heavy data is not stored inside task_struct itself. The struct holds pointers to other structs, and several tasks can share the same one. Threads of one program share one mm_struct, for example. Here is the picture:</p><pre>real_parent, parent<br>          ^<br>          |<br>  +-------+---------------+<br>  |      task_struct      |        +----------------+<br>  |                       |--mm---&gt;| mm_struct      |  memory map<br>  |  __state, flags       |        +----------------+<br>  |  pid, tgid, comm      |        +----------------+<br>  |  prio, se, policy     |-files-&gt;| files_struct   |  open files<br>  |                       |        +----------------+<br>  |  children  (head) ----+--&gt; list of child tasks<br>  |  sibling   (node) ----+--&gt; link in parent&#39;s children list<br>  |  tasks     (node) ----+--&gt; link in list of all processes<br>  |                       |        +----------------+<br>  |                       |--fs---&gt;| fs_struct      |  root, cwd, umask<br>  |                       |        +----------------+<br>  |                       |        +----------------+<br>  |                       |-signal&gt;| signal_struct  |  shared signal data, rlimits<br>  |                       |        +----------------+<br>  |                       |        +----------------+<br>  |                       |sighand&gt;| sighand_struct |  signal handlers<br>  |                       |        +----------------+<br>  |                       |        +----------------+<br>  |                       |--cred-&gt;| cred           |  uid, gid, capabilities<br>  |                       |        +----------------+<br>  |                       |        +----------------+<br>  |                       |nsproxy&gt;| nsproxy        |  namespaces<br>  +-----------------------+        +----------------+</pre><p>The parent and child links are just pointers and list_head nodes inside task_struct. The arrows on the right are plain pointers. If two threads share memory, their mm pointers hold the same address.</p><h3>Process state and flags in task_struct</h3><pre>struct task_struct {<br>    unsigned int   __state;      /* TASK_RUNNING, TASK_INTERRUPTIBLE, ... */<br>    unsigned int   saved_state;<br>    unsigned int   flags;        /* PF_* flags */<br>    unsigned int   ptrace;<br>    unsigned long  atomic_flags;<br>    unsigned long  jobctl;<br>    /* ... */<br>};</pre><ul><li><strong>__state</strong> (unsigned int): The current state of the task. It holds values like TASK_RUNNING, TASK_INTERRUPTIBLE, TASK_UNINTERRUPTIBLE, __TASK_STOPPED or __TASK_TRACED. In 2.6 kernels this field was called state and was a long. It was renamed in Linux 5.14 so that code has to use helpers like READ_ONCE() and set_current_state() instead of touching it directly.</li><li><strong>saved_state</strong> (unsigned int): A place to keep the old state while a task sleeps on a lock in real time kernels. The kernel puts the old state back when the lock is taken.</li><li><strong>flags</strong> (unsigned int): Per task flags that start with PF_. For example PF_KTHREAD means this is a kernel thread, PF_EXITING means it is shutting down and PF_IDLE marks the idle task.</li><li><strong>ptrace</strong> (unsigned int): Non zero when a debugger is tracing this task. It holds PT_* bits about how it is traced.</li><li><strong>atomic_flags</strong> (unsigned long): A second set of flags that must be changed atomically, like PFA_NO_NEW_PRIVS and some CPU security mitigation bits.</li><li><strong>jobctl</strong> (unsigned long): Job control bits, used when a task is being stopped with SIGSTOP or traced.</li></ul><p>What does a task state mean in plain words? TASK_RUNNING means the task is on a CPU or ready to run. TASK_INTERRUPTIBLE means it is sleeping and a signal can wake it up. TASK_UNINTERRUPTIBLE means it is sleeping and signals will not wake it. That is the D you see in ps. Newer kernels also combine bits, like TASK_KILLABLE, which is uninterruptible sleep that still wakes up for a fatal signal, and TASK_IDLE.</p><p>When you read State: in /proc/&lt;pid&gt;/status, the letter you see (R, S, D, T, Z and so on) comes from this field plus exit_state.</p><h3>Identity: pid and tgid in the Linux kernel</h3><pre>struct task_struct {<br>    pid_t               pid;<br>    pid_t               tgid;<br>    struct pid         *thread_pid;<br>    struct hlist_node   pid_links[PIDTYPE_MAX];<br>    struct list_head    thread_node;<br>    char                comm[TASK_COMM_LEN];   /* TASK_COMM_LEN is 16 */<br>    /* ... */<br>};</pre><ul><li><strong>pid</strong> (pid_t): The ID of this one task. Every thread has its own pid. In user space this is what gettid() returns.</li><li><strong>tgid</strong> (pid_t): The thread group ID. It is the pid of the first thread in the group, the group leader. In user space this is what getpid() returns, so all threads of one program report the same number.</li><li><strong>thread_pid</strong> (struct pid *): A pointer to the kernel&#39;s struct pid object for this task. That object knows the task&#39;s number in each PID namespace.</li><li><strong>pid_links</strong> (struct hlist_node[]): Links that hook this task onto the task lists of its struct pid objects, one per PID type (PID, TGID, PGID, SID). In 2.6 kernels this was the pids[] array, which was also used for the PID hash tables. The current layout came in around Linux 4.19.</li><li><strong>thread_node</strong> (struct list_head): This task&#39;s link in the list of all threads of its thread group. That list lives in signal_struct. Older kernels also had a thread_group list in the task itself.</li><li><strong>comm</strong> (char[16]): The short name of the program, without the path. It is what ps and top show, and it is cut to 15 characters plus the ending zero. Kernel code should change it with set_task_comm().</li></ul><p>So what is the difference between pid and tgid? For a single threaded program they are equal. When a program starts more threads, each new thread gets a new pid, but they all keep the leader&#39;s tgid. That is why the kernel calls a thread &quot;a task&quot; too. It is a full task_struct that shares some pointers with its siblings.</p><h3>Family links: real_parent, parent, children and sibling</h3><pre>struct task_struct {<br>    struct task_struct __rcu  *real_parent;<br>    struct task_struct __rcu  *parent;<br>    struct list_head           children;<br>    struct list_head           sibling;<br>    struct task_struct        *group_leader;<br>    struct list_head           ptraced;<br>    struct list_head           ptrace_entry;<br>    struct list_head           tasks;<br>    /* ... */<br>};</pre><ul><li><strong>real_parent</strong> (struct task_struct *): The task that created this one with fork() or clone(). If that parent exits first, the child gets a new parent, usually init (PID 1) or a subreaper. This is what getppid() reports.</li><li><strong>parent</strong> (struct task_struct *): The task that gets notified with SIGCHLD and wait() results when this task changes state. It is normally the same as real_parent. It differs while a debugger is tracing the task with ptrace().</li><li><strong>children</strong> (struct list_head): The head of the list of this task&#39;s children.</li><li><strong>sibling</strong> (struct list_head): This task&#39;s node in its parent&#39;s children list. So the parent holds the list head and each child holds a node.</li><li><strong>group_leader</strong> (struct task_struct *): Points to the leader of this thread group. For the leader it points to itself.</li><li><strong>ptraced</strong> (struct list_head): The list of tasks this task is tracing as a debugger. In 2.6 kernels it was ptrace_children.</li><li><strong>ptrace_entry</strong> (struct list_head): This task&#39;s node in its tracer&#39;s ptraced list. In 2.6 kernels it was ptrace_list.</li><li><strong>tasks</strong> (struct list_head): This task&#39;s node in the big list of all processes. The list starts at init_task, the descriptor of process 0. The for_each_process() macro walks it.</li></ul><p>The children, sibling and tasks fields are list_head nodes embedded in the struct. The kernel walks from a node back to its task_struct with container_of(). I will cover how that trick works in the linked list posts later, so I am keeping it short here.</p><p>Process group and session IDs used to be fields in the task too (pgrp and session in very old kernels, then signal-&gt;pgrp). Today the kernel gets them through signal_struct and struct pid.</p><h3>Scheduling fields in the Linux kernel task_struct</h3><pre>struct task_struct {<br>    u8                           on_cpu;<br>    u8                           on_rq;<br>    int                          prio;<br>    int                          static_prio;<br>    int                          normal_prio;<br>    unsigned int                 rt_priority;<br>    struct sched_entity          se;<br>    struct sched_rt_entity       rt;<br>    struct sched_dl_entity       dl;<br>    const struct sched_class    *sched_class;<br>    unsigned int                 policy;<br>    int                          nr_cpus_allowed;<br>    const cpumask_t             *cpus_ptr;<br>    cpumask_t                    cpus_mask;<br>    int                          recent_used_cpu;<br>    int                          wake_cpu;<br>    struct sched_info            sched_info;<br>    unsigned long                nvcsw;<br>    unsigned long                nivcsw;<br>    /* ... */<br>};</pre><ul><li><strong>on_cpu</strong> (u8): Set to 1 while the task is actually running on a CPU.</li><li><strong>on_rq</strong> (u8): Says whether the task is on a run queue, meaning it is ready to run and waiting its turn.</li><li><strong>prio</strong> (int): The priority the scheduler really uses right now. It can be raised for a short time, for example when this task holds a lock a higher priority task needs. Lower number means higher priority.</li><li><strong>static_prio</strong> (int): The priority that comes from the nice value. Nice 0 maps to 120, nice -20 to 100 and nice 19 to 139.</li><li><strong>normal_prio</strong> (int): The priority the task would have without any temporary boost. It is worked out from static_prio or rt_priority and the policy.</li><li><strong>rt_priority</strong> (unsigned int): The real time priority, from 1 to 99, for tasks using SCHED_FIFO or SCHED_RR. It is 0 for normal tasks.</li><li><strong>se</strong> (struct sched_entity): The data the fair scheduler (CFS, and EEVDF since 6.6) keeps for this task. It includes vruntime and sum_exec_runtime, the total CPU time used.</li><li><strong>rt</strong> (struct sched_rt_entity): Data for the real time scheduler. Its run_list field links the task into a real time priority queue.</li><li><strong>dl</strong> (struct sched_dl_entity): Data for the deadline scheduler (SCHED_DEADLINE), like runtime, deadline and period.</li><li><strong>sched_class</strong> (const struct sched_class *): A pointer to a table of functions for the scheduler class that owns this task: fair, real time, deadline, idle or stop. This is the kernel&#39;s &quot;ops table&quot; idea, which I will cover later in the series.</li><li><strong>policy</strong> (unsigned int): The scheduling policy: SCHED_NORMAL, SCHED_BATCH, SCHED_IDLE, SCHED_FIFO, SCHED_RR or SCHED_DEADLINE.</li><li><strong>nr_cpus_allowed</strong> (int): How many CPUs this task may run on.</li><li><strong>cpus_mask</strong> (cpumask_t): The set of CPUs this task may run on, the CPU affinity. taskset changes it. In 2.6 kernels it was called cpus_allowed. It was renamed in Linux 5.3.</li><li><strong>cpus_ptr</strong> (const cpumask_t *): A pointer the scheduler reads instead of cpus_mask directly. It normally points to cpus_mask, but it can point somewhere else for a short time, like when migration is disabled.</li><li><strong>recent_used_cpu</strong> (int): A CPU this task ran on recently. The scheduler uses it to pick a warm CPU when the task wakes up.</li><li><strong>wake_cpu</strong> (int): The CPU picked to run the task when it is woken up.</li><li><strong>sched_info</strong> (struct sched_info): Scheduler statistics like how long the task waited on the run queue and how many times it ran.</li><li><strong>nvcsw</strong> (unsigned long): Number of voluntary context switches. The task gave up the CPU on its own, for example to wait for I/O. Shown as voluntary_ctxt_switches in /proc/&lt;pid&gt;/status.</li><li><strong>nivcsw</strong> (unsigned long): Number of involuntary context switches. The scheduler took the CPU away. Shown as nonvoluntary_ctxt_switches.</li></ul><p>If you read older material you will see different scheduling fields. The 2.6 O(1) scheduler had run_list and array directly in the task, pointing into a prio_array_t with 140 priority lists. It also had sleep_avg, timestamp, last_ran, activated, time_slice and first_time_slice. All of those went away in Linux 2.6.23 when CFS arrived and the per task data moved into struct sched_entity se. The sched_class pointer came in at the same time.</p><h3>Memory: mm and active_mm</h3><pre>struct task_struct {<br>    struct mm_struct  *mm;<br>    struct mm_struct  *active_mm;<br>    /* ... */<br>};</pre><ul><li><strong>mm</strong> (struct mm_struct *): The memory descriptor for this task&#39;s user address space. It holds the list of memory areas, the page tables and counters like resident memory. All threads of a process point to the same mm_struct. For kernel threads mm is NULL, because they have no user space.</li><li><strong>active_mm</strong> (struct mm_struct *): The address space that is actually loaded while this task runs. For normal tasks it equals mm. A kernel thread borrows the mm of the task that ran before it, so it does not have to switch page tables. This is called lazy TLB.</li></ul><p>A simple test you will see in kernel code is if (!p-&gt;mm). It is one quick way to tell a kernel thread from a user task, though modern code prefers checking PF_KTHREAD in flags.</p><h3>Credentials: cred and real_cred</h3><pre>struct task_struct {<br>    const struct cred __rcu  *ptracer_cred;<br>    const struct cred __rcu  *real_cred;<br>    const struct cred        *cred;<br>    /* ... */<br>};</pre><ul><li><strong>real_cred</strong> (const struct cred *): The objective credentials. This is who the task really is when other tasks act on it, for example when someone sends it a signal.</li><li><strong>cred</strong> (const struct cred *): The subjective credentials. This is who the task acts as when it opens a file or does other work. It is usually the same object as real_cred, but the kernel can override it for a short time.</li><li><strong>ptracer_cred</strong> (const struct cred *): The credentials of the debugger at the moment it attached. Used for security checks while tracing.</li></ul><p>Inside struct cred you find uid, gid, euid, egid, suid, sgid, fsuid, fsgid, the supplementary groups and the capability sets. In 2.6 kernels up to 2.6.28, those IDs were plain fields right inside task_struct, like current-&gt;uid and current-&gt;euid. Since 2.6.29 you read them through the cred, for example with current_uid() or task_euid(p). A cred is never changed in place. To change one the kernel makes a new copy and swaps the pointer.</p><h3>Files and filesystem: files and fs</h3><pre>struct task_struct {<br>    struct fs_struct     *fs;<br>    struct files_struct  *files;<br>    struct nameidata     *nameidata;<br>    /* ... */<br>};</pre><ul><li><strong>fs</strong> (struct fs_struct *): Filesystem context: the root directory, the current working directory and the umask. chdir() and chroot() change what this points to.</li><li><strong>files</strong> (struct files_struct *): The open file table. A file descriptor like 0, 1 or 3 is an index into the array of struct file pointers inside it. Threads usually share one files_struct.</li><li><strong>nameidata</strong> (struct nameidata *): Temporary state used while the kernel walks a path name like /home/me/a.txt.</li></ul><p>Mainline also has a real_fs field next to fs. It is a very recent addition in the 7.x kernels and is not in 6.12, so you will not see it in most material yet.</p><p>When you run ls -l /proc/self/fd, the kernel is reading this task&#39;s files table. When you look at /proc/self/cwd, it reads fs.</p><h3>Signals in the Linux kernel task_struct</h3><pre>struct task_struct {<br>    struct signal_struct         *signal;<br>    struct sighand_struct __rcu  *sighand;<br>    sigset_t                      blocked;<br>    sigset_t                      real_blocked;<br>    sigset_t                      saved_sigmask;<br>    struct sigpending             pending;<br>    unsigned long                 sas_ss_sp;<br>    size_t                        sas_ss_size;<br>    unsigned int                  sas_ss_flags;<br>    int                           pdeath_signal;<br>    /* ... */<br>};</pre><ul><li><strong>signal</strong> (struct signal_struct *): Signal and process wide data shared by all threads in the group. It has the shared pending signals, the thread list, resource limits in rlim[], process group and session info, and group wide CPU time totals.</li><li><strong>sighand</strong> (struct sighand_struct *): The table of signal handlers, what to do for each signal. Threads share it, which is why a handler set in one thread applies to all.</li><li><strong>blocked</strong> (sigset_t): The mask of signals this thread has blocked. sigprocmask() and pthread_sigmask() change it.</li><li><strong>real_blocked</strong> (sigset_t): A saved copy of the mask, used by calls like rt_sigtimedwait() that change the mask for a while.</li><li><strong>saved_sigmask</strong> (sigset_t): The mask to restore after calls like sigsuspend() or ppoll() return.</li><li><strong>pending</strong> (struct sigpending): Signals sent to this one thread that are not handled yet. Signals sent to the whole process go into signal-&gt;shared_pending instead.</li><li><strong>sas_ss_sp</strong> (unsigned long): Start address of the alternate signal stack set with sigaltstack().</li><li><strong>sas_ss_size</strong> (size_t): Size of that alternate stack.</li><li><strong>sas_ss_flags</strong> (unsigned int): Flags for the alternate stack.</li><li><strong>pdeath_signal</strong> (int): The signal this task gets when its parent dies. You set it with prctl(PR_SET_PDEATHSIG).</li></ul><p>Resource limits like RLIMIT_NOFILE live in current-&gt;signal-&gt;rlim, not in the task. That has been the case since 2.6, and it is because limits are per process, not per thread.</p><h3>Kernel stack and thread_info: where does the task live?</h3><pre>struct task_struct {<br>#ifdef CONFIG_THREAD_INFO_IN_TASK<br>    struct thread_info   thread_info;   /* must be first */<br>#endif<br>    void                *stack;<br>    refcount_t           stack_refcount;<br>    struct vm_struct    *stack_vm_area;<br>    /* ... */<br>    struct thread_struct thread;        /* must be last */<br>};</pre><ul><li><strong>thread_info</strong> (struct thread_info): Small, arch specific data that low level code needs fast, like the TIF_NEED_RESCHED and TIF_SIGPENDING flags. On x86 and arm64 it is the very first member of task_struct.</li><li><strong>stack</strong> (void *): Points to the bottom of this task&#39;s kernel stack. Each task has its own kernel stack, used when it runs in kernel mode. On x86-64 it is 16 KB.</li><li><strong>stack_vm_area</strong> (struct vm_struct *): When the kernel stack is allocated with vmalloc (CONFIG_VMAP_STACK), this points to that area. A guard page there turns a stack overflow into a clean crash instead of silent memory damage.</li><li><strong>stack_refcount</strong> (refcount_t): A count of users of the stack, so it is not freed while someone still needs it.</li><li><strong>thread</strong> (struct thread_struct): The CPU specific saved state used during a context switch, like the saved stack pointer, segment and debug registers, and FPU state. It is kept as the last member because its size can change.</li></ul><p>This is one of the areas that changed the most. In 2.6 kernels on x86, thread_info sat at the bottom of an 8 KB kernel stack area (a union thread_union). The task had a thread_info pointer to it and thread_info had a task pointer back. To find the current task, the kernel masked the low bits of the stack pointer to reach thread_info, then followed -&gt;task. Today x86 sets CONFIG_THREAD_INFO_IN_TASK (since Linux 4.9), so thread_info moved inside task_struct and the stack area holds only the stack.</p><h3>How does the Linux kernel find the current task_struct?</h3><p>Kernel code writes current and gets a pointer to the running task. For example current-&gt;pid or current-&gt;comm.</p><p>On modern x86–64, current reads a per CPU variable called current_task. The scheduler writes the new task&#39;s address into it on every context switch, so reading it is a single instruction. Other architectures keep the pointer in a register, for example sp_el0 on arm64. On old 2.6 x86 kernels, current was found from the stack pointer as I described in the section above.</p><h3>Time accounting fields in the Linux kernel task_struct</h3><pre>struct task_struct {<br>    u64            utime;<br>    u64            stime;<br>    u64            gtime;<br>    u64            start_time;<br>    u64            start_boottime;<br>    unsigned long  min_flt;<br>    unsigned long  maj_flt;<br>    struct task_io_accounting ioac;<br>    /* ... */<br>};</pre><ul><li><strong>utime</strong> (u64): CPU time this task spent in user mode, in nanoseconds.</li><li><strong>stime</strong> (u64): CPU time this task spent in kernel mode, in nanoseconds.</li><li><strong>gtime</strong> (u64): Time spent running a virtual machine guest, for KVM vCPU threads.</li><li><strong>start_time</strong> (u64): When the task started, in nanoseconds of monotonic time. Monotonic time does not count time while the machine was suspended.</li><li><strong>start_boottime</strong> (u64): When the task started, in nanoseconds since boot including suspend time. This is what feeds the start time column in /proc/&lt;pid&gt;/stat.</li><li><strong>min_flt</strong> (unsigned long): Minor page faults: the page was already in memory and only needed mapping.</li><li><strong>maj_flt</strong> (unsigned long): Major page faults: the page had to be read from disk.</li><li><strong>ioac</strong> (struct task_io_accounting): Bytes read and written, shown in /proc/&lt;pid&gt;/io.</li></ul><p>In 2.6 kernels utime and stime were of type cputime_t, counted in ticks, and start_time was a struct timespec. Today they are plain u64 nanoseconds. Totals for the whole thread group, including dead threads, are kept in signal_struct.</p><h3>Exit fields: exit_state, exit_code and exit_signal</h3><pre>struct task_struct {<br>    int  exit_state;<br>    int  exit_code;<br>    int  exit_signal;<br>    struct completion *vfork_done;<br>    int __user        *set_child_tid;<br>    int __user        *clear_child_tid;<br>    /* ... */<br>};</pre><ul><li><strong>exit_state</strong> (int): Set when the task has finished. EXIT_ZOMBIE means it is dead but the parent has not called wait() yet. EXIT_DEAD means it is being removed for good.</li><li><strong>exit_code</strong> (int): The exit status and signal info that the parent reads with wait().</li><li><strong>exit_signal</strong> (int): The signal sent to the parent when this task exits, normally SIGCHLD. For threads it is -1, because a thread exiting does not notify the parent process.</li><li><strong>vfork_done</strong> (struct completion *): Used by vfork(). The parent sleeps on it until the child calls exec or exits.</li><li><strong>set_child_tid</strong> (int __user *): A user space address where the kernel writes the new thread&#39;s ID at start. Thread libraries use it.</li><li><strong>clear_child_tid</strong> (int __user *): A user space address that the kernel clears and wakes with a futex when the thread exits. This is how pthread_join() knows a thread is done.</li></ul><p>A zombie is just a task_struct that stays around holding exit_code and the time totals until the parent collects them. Almost all its other resources are already freed.</p><h3>Namespaces and cgroups: how containers use task_struct in the Linux kernel</h3><pre>struct task_struct {<br>    struct nsproxy        *nsproxy;<br>    struct css_set __rcu  *cgroups;<br>    struct list_head       cg_list;<br>    /* ... */<br>};</pre><ul><li><strong>nsproxy</strong> (struct nsproxy *): Points to the set of namespaces the task lives in: UTS, IPC, mount, network, PID for children, time and cgroup. Containers are built on this. In early 2.6 kernels there was only a namespace field for mount namespaces. nsproxy came in 2.6.19.</li><li><strong>cgroups</strong> (struct css_set *): The set of control groups this task belongs to. Limits like memory and CPU for containers and systemd services come from here.</li><li><strong>cg_list</strong> (struct list_head): This task&#39;s node in the list of tasks that share the same css_set.</li></ul><p>The user and PID namespaces are not stored directly in nsproxy for the task itself. The user namespace sits in cred, and the task&#39;s own PID namespace comes from its struct pid.</p><h3>Reference counting and lifetime</h3><pre>struct task_struct {<br>    refcount_t       usage;<br>    refcount_t       rcu_users;<br>    struct rcu_head  rcu;<br>    spinlock_t       alloc_lock;<br>    raw_spinlock_t   pi_lock;<br>    /* ... */<br>};</pre><ul><li><strong>usage</strong> (refcount_t): How many places hold a reference to this task_struct. get_task_struct() adds one and put_task_struct() drops one. The struct is freed when it reaches zero. In 2.6 kernels it was an atomic_t.</li><li><strong>rcu_users</strong> (refcount_t): A second count for users that read the task under RCU. When it drops to zero, the kernel waits for an RCU grace period and then drops one usage reference.</li><li><strong>rcu</strong> (struct rcu_head): Used to free the task safely after all RCU readers are done.</li><li><strong>alloc_lock</strong> (spinlock_t): Protects several pointers like mm, files, fs and comm while they are being changed. task_lock(p) takes it.</li><li><strong>pi_lock</strong> (raw_spinlock_t): Protects the priority inheritance data and is also taken when waking the task up.</li></ul><p>Why two counts? Many parts of the kernel only peek at a task under rcu_read_lock() and do not want to pay for a full reference. The two counters let both styles of access work.</p><h3>Other fields worth knowing</h3><p>These do not fit neatly in the groups above, but you will meet them when reading kernel code.</p><ul><li><strong>personality</strong> (unsigned int): Execution domain flags, set with personality(). Used for things like disabling address space randomization for one program.</li><li><strong>restart_block</strong> (struct restart_block): Information to restart a system call that was interrupted, like nanosleep().</li><li><strong>stack_canary</strong> (unsigned long): A random value used by the compiler&#39;s stack protector to catch stack smashing in kernel code.</li><li><strong>seccomp</strong> (struct seccomp): The seccomp mode and filters for this task. Browsers and container runtimes use it to limit which system calls a process may make.</li><li><strong>audit_context</strong> (struct audit_context *): Data for the audit subsystem while a system call is being audited.</li><li><strong>loginuid</strong> (kuid_t): The user ID that logged in, kept for auditing even after su or sudo.</li><li><strong>sessionid</strong> (unsigned int): The audit login session ID.</li><li><strong>self_exec_id</strong> (u64): Goes up by one on every exec. The kernel uses it, for example, to decide if a child&#39;s exit signal should be reset because the parent ran a new program.</li><li><strong>parent_exec_id</strong> (u64): The parent&#39;s self_exec_id at fork time.</li><li><strong>journal_info</strong> (void *): Pointer used by journaling filesystems like ext4 to track the current transaction.</li><li><strong>io_context</strong> (struct io_context *): Block I/O scheduler data for this task, like its I/O priority.</li><li><strong>sysvsem</strong> (struct sysv_sem): System V semaphore undo info, so semaphore changes can be undone if the task dies.</li><li><strong>mempolicy</strong> (struct mempolicy *): The NUMA memory policy set with set_mempolicy().</li><li><strong>mems_allowed</strong> (nodemask_t): The NUMA nodes this task may take memory from, set by cpusets.</li><li><strong>delays</strong> (struct task_delay_info *): Delay accounting: time spent waiting for CPU, I/O and memory.</li><li><strong>task_works</strong> (struct callback_head *): A list of small jobs to run when the task next returns to user space.</li><li><strong>io_uring</strong> (struct io_uring_task *): Per task data for io_uring.</li><li><strong>perf_event_ctxp</strong> (struct perf_event_context *): Performance counter data used by perf.</li><li><strong>security</strong> (void *): Private data for security modules like SELinux or AppArmor.</li><li><strong>timer_slack_ns</strong> (u64): How much the kernel may delay this task&#39;s timers to group wakeups and save power.</li><li><strong>pagefault_disabled</strong> (int): Counter that is non zero while page faults are disabled for this task.</li></ul><p>There are many more, mostly for debugging tools (lockdep, KASAN, KCSAN, KCOV, ftrace), NUMA balancing, real time locking and memory cgroups. They are each behind a config option, and most kernel developers never touch them.</p><h3>How do you see task_struct fields from user space in Linux?</h3><p>You cannot read task_struct directly from a normal program. It lives in kernel memory. But the kernel copies many of its fields out to you through system calls and through /proc.</p><p>Here is a small program that shows the difference between pid and tgid. It starts one extra thread and prints the IDs from both threads.</p><pre>#define _GNU_SOURCE<br>#include &lt;stdio.h&gt;<br>#include &lt;pthread.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;sys/syscall.h&gt;</pre><pre>static void *worker(void *arg)<br>{<br>    (void)arg;<br>    /* getpid() returns tgid, gettid() returns this thread&#39;s own pid */<br>    printf(&quot;thread: getpid() = %d  gettid() = %ld\n&quot;,<br>           getpid(), (long)syscall(SYS_gettid));<br>    return NULL;<br>}</pre><pre>int main(void)<br>{<br>    pthread_t t;</pre><pre>    printf(&quot;main:   getpid() = %d  gettid() = %ld  getppid() = %d\n&quot;,<br>           getpid(), (long)syscall(SYS_gettid), getppid());</pre><pre>    pthread_create(&amp;t, NULL, worker, NULL);<br>    pthread_join(t, NULL);<br>    return 0;<br>}</pre><p>Build and run it:</p><pre>gcc -Wall -o ids ids.c -pthread<br>./ids</pre><p>Sample output (your numbers will differ):</p><pre>main:   getpid() = 16724  gettid() = 16724  getppid() = 16707<br>thread: getpid() = 16724  gettid() = 16725</pre><p>Both threads print the same getpid(). That is tgid. The thread has its own gettid(). That is its own pid field. The main thread is the group leader, so its pid and tgid match. getppid() comes from real_parent, which here is the shell.</p><p>The second program reads /proc/self/status. This file is built by the kernel from the current task_struct and the structs it points to. The program prints only the lines that map to the fields in this post.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;</pre><pre>/* Print the lines of /proc/self/status that come from task_struct */<br>int main(void)<br>{<br>    const char *keys[] = {<br>        &quot;Name:&quot;, &quot;State:&quot;, &quot;Tgid:&quot;, &quot;Pid:&quot;, &quot;PPid:&quot;,<br>        &quot;Uid:&quot;, &quot;Gid:&quot;, &quot;Threads:&quot;, &quot;Cpus_allowed_list:&quot;,<br>        &quot;voluntary_ctxt_switches:&quot;, &quot;nonvoluntary_ctxt_switches:&quot;<br>    };<br>    size_t nkeys = sizeof(keys) / sizeof(keys[0]);<br>    char line[256];<br>    FILE *f = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);</pre><pre>    if (f == NULL) {<br>        perror(&quot;fopen&quot;);<br>        return 1;<br>    }</pre><pre>    while (fgets(line, sizeof(line), f) != NULL) {<br>        for (size_t i = 0; i &lt; nkeys; i++) {<br>            if (strncmp(line, keys[i], strlen(keys[i])) == 0) {<br>                fputs(line, stdout);<br>                break;<br>            }<br>        }<br>    }</pre><pre>    fclose(f);<br>    return 0;<br>}</pre><pre>gcc -Wall -o status status.c<br>./status</pre><p>Sample output:</p><pre>Name:   status<br>State:  R (running)<br>Tgid:   16726<br>Pid:    16726<br>PPid:   16707<br>Uid:    1000    1000    1000    1000<br>Gid:    1000    1000    1000    1000<br>Threads:    1<br>Cpus_allowed_list:  0-7<br>voluntary_ctxt_switches:    0<br>nonvoluntary_ctxt_switches: 0</pre><p>Here is where each line comes from:</p><ul><li><strong>Name</strong>: comm</li><li><strong>State</strong>: __state and exit_state</li><li><strong>Tgid, </strong><strong>Pid</strong>: tgid, pid (as seen in your PID namespace)</li><li><strong>PPid</strong>: real_parent</li><li><strong>Uid, </strong><strong>Gid</strong>: real_cred (real, effective, saved and filesystem IDs)</li><li><strong>Threads</strong>: signal-&gt;nr_threads</li><li><strong>Cpus_allowed_list</strong>: cpus_ptr</li><li><strong>voluntary_ctxt_switches</strong>: nvcsw</li><li><strong>nonvoluntary_ctxt_switches</strong>: nivcsw</li></ul><p>The State is R because the program is running while it reads its own status. Try cat /proc/1/status or look at another process with ps and you will see S for sleeping.</p><h3>A tiny Linux kernel module that reads task_struct</h3><p>If you want to touch the real struct, a kernel module can. This one prints the task that loaded it, then walks the process list and prints the first ten tasks with their parent’s PID.</p><pre>// ts_demo.c: print the current task and the first few processes<br>#include &lt;linux/module.h&gt;<br>#include &lt;linux/sched.h&gt;<br>#include &lt;linux/sched/signal.h&gt;   /* for_each_process() */<br>#include &lt;linux/rcupdate.h&gt;</pre><pre>static int __init ts_demo_init(void)<br>{<br>    struct task_struct *p;<br>    int n = 0;</pre><pre>    pr_info(&quot;ts_demo: loaded by %s, pid=%d tgid=%d\n&quot;,<br>            current-&gt;comm, current-&gt;pid, current-&gt;tgid);</pre><pre>    rcu_read_lock();<br>    for_each_process(p) {<br>        pr_info(&quot;ts_demo: %-16s pid=%d ppid=%d\n&quot;,<br>                p-&gt;comm, p-&gt;pid,<br>                rcu_dereference(p-&gt;real_parent)-&gt;tgid);<br>        if (++n &gt;= 10)<br>            break;<br>    }<br>    rcu_read_unlock();<br>    return 0;<br>}</pre><pre>static void __exit ts_demo_exit(void)<br>{<br>    pr_info(&quot;ts_demo: unloaded\n&quot;);<br>}</pre><pre>module_init(ts_demo_init);<br>module_exit(ts_demo_exit);<br>MODULE_LICENSE(&quot;GPL&quot;);<br>MODULE_DESCRIPTION(&quot;Walk task_struct fields from a module&quot;);</pre><p>Note: I have not compiled or loaded this module. It is written against the mainline headers, but treat it as a sketch. To build it you need the headers for your running kernel and a two line Makefile with obj-m += ts_demo.o. After sudo insmod ts_demo.ko, read the output with sudo dmesg | tail, and remove it with sudo rmmod ts_demo.</p><p>A few things to notice. current is the task that ran insmod, so its comm is insmod. The walk is done inside rcu_read_lock(), because tasks can exit while we look at the list, and real_parent is an RCU protected pointer. Do not try this on a machine you care about. A bad pointer inside a module can crash the whole system.</p><p>That is the whole process descriptor, one group at a time. In the next posts of this C struct series we go back to smaller building blocks, and you will keep seeing pieces of task_struct as examples. If you want to get solid on C structs and pointers first, the <a href="https://www.jupiuslearning.com/courses/c-prog-a/">Jupius C programming course</a> covers them with live evaluation.</p><h3>Frequently asked questions</h3><h3>What is task_struct in Linux?</h3><p>task_struct is the C struct the Linux kernel uses to describe one process or thread. It holds the task&#39;s state, IDs, parent links, scheduling data and pointers to its memory, open files, credentials and signal handlers. It is also called the process descriptor.</p><h3>Where is task_struct defined in the Linux kernel?</h3><p>It is defined in include/linux/sched.h in the kernel source tree. Some parts it points to are defined elsewhere, like mm_struct in include/linux/mm_types.h and signal_struct in include/linux/sched/signal.h.</p><h3>How big is task_struct?</h3><p>It is several kilobytes on a typical modern 64-bit kernel, and the exact size varies with the kernel version, the CPU architecture and which config options are on. Distribution kernels with more debug and tracing options turned on are often bigger.</p><p>You can check the size on your own machine. One way is sudo grep task_struct /proc/slabinfo. The objsize column is the size of one task_struct in bytes. Another way, if you have the kernel debug info and the pahole tool, is to run pahole -C task_struct against the kernel&#39;s vmlinux.</p><h3>What is the difference between pid and tgid in Linux?</h3><p>pid is the ID of one task, and every thread has its own. tgid is the thread group ID, which is the pid of the first thread in the process. The getpid() call returns tgid, and gettid() returns pid.</p><h3>How does the Linux kernel find the current task_struct?</h3><p>Kernel code uses the current macro. On x86-64 it reads a per CPU variable that the scheduler updates on every context switch. Old 2.6 x86 kernels found it by masking the stack pointer to reach thread_info and then following its task pointer.</p><h3>Is a thread a task_struct in Linux?</h3><p>Yes. Every thread has its own task_struct with its own pid, state and kernel stack. Threads of the same process share the same tgid and point to the same mm_struct, files_struct, fs_struct, signal_struct and sighand_struct.</p><p>Originally published on <a href="https://www.jupiuslearning.com/blog/task-struct-linux-kernel-every-field-explained/">Jupius Learning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6190a1759899" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First C Struct: Declare, Fill and Read It (Linux Kernel Example)]]></title>
            <link>https://medium.com/@vadhernknj19/your-first-c-struct-declare-fill-and-read-it-linux-kernel-example-8d19d651bc51?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d19d651bc51</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 07:53:48 GMT</pubDate>
            <atom:updated>2026-11-17T07:53:48.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJeBIi368r-07SWf.jpg" /></figure><p>To use a struct in C, you first declare it. That means you write struct with a name and list its fields inside braces. Then you create a variable of that type and give each field a value, either all at once with { } or one field at a time. You read any field back with a dot, like s1.marks.</p><p>In the <a href="https://www.jupiuslearning.com/blog/the-humble-c-struct-that-still-runs-billions-of-machines/">last post</a> I talked about why the plain C struct matters so much, and how the Linux kernel is built out of structs. This time we write one ourselves. Nothing fancy. We will declare a struct, put values in it and read them back. Then we will look at a tiny struct the Linux kernel uses to keep track of the time, and see that it works the same way.</p><h3>How do you declare a struct in C?</h3><p>A struct declaration describes the shape of your data. It says what fields there are and what type each one has.</p><pre>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>};</pre><p>A few small things to notice here. The word after struct is the tag, here student. Together, struct student is the name of your new type. Each line inside the braces is one field, also called a member. And there is a semicolon after the closing brace. Beginners forget that one a lot, and the compiler error you get is not always clear.</p><p>This code does not create any student yet. It only tells the compiler what a student looks like. Think of it as a form with empty boxes. No memory is used for data until you make a variable.</p><h3>How do you fill a struct with values?</h3><p>Now we make a variable of that type and put values into it. There are two common ways.</p><p>The first way is to give all the values when you create the variable. The values go inside braces, in the same order as the fields.</p><pre>struct student s1 = { 1, &quot;Asha&quot;, 87.5f };</pre><p>So roll_no gets 1, name gets &quot;Asha&quot; and marks gets 87.5. If the order is wrong, C will not always complain. It just puts the values in the wrong boxes, so be careful.</p><p>The second way is to create the variable first and set each field on its own line. Starting with = { 0 } sets every field to zero, so nothing holds garbage while you fill it.</p><pre>struct student s2 = { 0 };<br>s2.roll_no = 2;<br>strcpy(s2.name, &quot;Ravi&quot;);<br>s2.marks = 91.0f;</pre><p>Notice the strcpy for the name. You cannot write s2.name = &quot;Ravi&quot;; because name is an array, and C does not let you assign to an array after it is created. Inside the { } at creation time it is fine, which is why s1 worked.</p><p>There is a third style, where you name each field inside the braces. The Linux kernel uses it all over the place. It gets its own post later in this series, so I will leave it for now.</p><h3>How do you read a struct field? The dot operator</h3><p>To get a value out, you write the variable name, a dot, then the field name. s1.name is Asha&#39;s name. s1.marks is her marks. You can use these anywhere you would use a normal variable. You can print them, or do math with them just like any other number.</p><p>You may have seen the arrow, -&gt;, in kernel code. That is for when you have a pointer to a struct instead of the struct itself. We will get to it a few posts from now. For today, everything is a plain variable, so the dot is all we need.</p><h3>A complete C example you can run</h3><p>Here is everything together in one program.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;</pre><pre>/* Step 1: declare the struct type */<br>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>};</pre><pre>int main(void)<br>{<br>    /* Step 2a: fill it when you create it */<br>    struct student s1 = { 1, &quot;Asha&quot;, 87.5f };</pre><pre>    /* Step 2b: or create it empty and fill it field by field */<br>    struct student s2 = { 0 };<br>    s2.roll_no = 2;<br>    strcpy(s2.name, &quot;Ravi&quot;);<br>    s2.marks = 91.0f;</pre><pre>    /* Step 3: read the fields with the dot operator */<br>    printf(&quot;%d %s %.1f\n&quot;, s1.roll_no, s1.name, s1.marks);<br>    printf(&quot;%d %s %.1f\n&quot;, s2.roll_no, s2.name, s2.marks);</pre><pre>    /* You can change a field later too */<br>    s1.marks = s1.marks + 2.5f;<br>    printf(&quot;%s now has %.1f\n&quot;, s1.name, s1.marks);</pre><pre>    return 0;<br>}</pre><p>Save it as student.c, then compile and run it:</p><pre>gcc student.c -o student<br>./student</pre><p>On Windows with MinGW installed, the second line in PowerShell is .\student.exe.</p><p>Output:</p><pre>1 Asha 87.5<br>2 Ravi 91.0<br>Asha now has 90.0</pre><p>That is the whole idea. Declare the shape once. Make as many variables of that type as you like. Each one keeps its own copy of the fields, so changing s1.marks does not touch s2.</p><h3>A real Linux kernel struct: timespec</h3><p>Now let us look at the Linux kernel. One of the simplest structs in it is struct timespec. The kernel keeps the current date and time in a variable called xtime, and xtime is a struct timespec. It has just two fields.</p><pre>/* Simplified from the Linux kernel */<br>struct timespec {<br>    long tv_sec;    /* seconds since midnight, 1 January 1970 (UTC) */<br>    long tv_nsec;   /* nanoseconds within the current second, 0 to 999,999,999 */<br>};</pre><p>That is a struct declaration, exactly like our student. Two fields that belong together, under one name. A time on its own in seconds is not precise enough, and nanoseconds on their own would overflow fast. Together they describe one moment.</p><p>The kernel fills xtime when the machine boots, by reading the seconds from the hardware clock. After that it keeps updating it as the timer ticks. On a typical setup, each tick adds 1,000,000 nanoseconds to xtime.tv_nsec. When tv_nsec goes past 999,999,999, a full second has passed, so the kernel bumps tv_sec by one and brings tv_nsec back down.</p><p>Look at that sentence again. xtime.tv_nsec. That is the same dot we used for s1.marks.</p><h3>How the Linux kernel updates a struct field: try it yourself</h3><p>We can copy that logic in a small program. I named the struct my_timespec so it does not clash with the real struct timespec that your system headers already define.</p><pre>#include &lt;stdio.h&gt;</pre><pre>/* Same two fields as the kernel&#39;s struct timespec */<br>struct my_timespec {<br>    long tv_sec;    /* seconds since 1 Jan 1970 (UTC) */<br>    long tv_nsec;   /* nanoseconds inside the current second */<br>};</pre><pre>int main(void)<br>{<br>    /* Fill it: almost at the end of a second */<br>    struct my_timespec now = { 1700000000, 999500000 };</pre><pre>    printf(&quot;before: %ld s, %ld ns\n&quot;, now.tv_sec, now.tv_nsec);</pre><pre>    /* One tick adds 1,000,000 ns (one millisecond) */<br>    now.tv_nsec = now.tv_nsec + 1000000;</pre><pre>    /* If nanoseconds go past one full second, carry into seconds */<br>    if (now.tv_nsec &gt; 999999999) {<br>        now.tv_nsec = now.tv_nsec - 1000000000;<br>        now.tv_sec = now.tv_sec + 1;<br>    }</pre><pre>    printf(&quot;after:  %ld s, %ld ns\n&quot;, now.tv_sec, now.tv_nsec);<br>    return 0;<br>}</pre><p>Output:</p><pre>before: 1700000000 s, 999500000 ns<br>after:  1700000001 s, 500000 ns</pre><p>We started half a millisecond before the end of a second. One tick pushed tv_nsec past a full second, so the code carried one second over into tv_sec. The real kernel code has more going on, like locking so that two CPUs do not update the time at once. But the struct part is just this: read a field with a dot, change it, write it back.</p><h3>Filling a struct the Linux kernel reads: struct flock</h3><p>Here is one more, and this time you fill a struct and the Linux kernel reads it. When a program wants to lock part of a file, it fills a struct flock and hands it to the fcntl() system call. The kernel then reads the fields to find out what you asked for. You can use this one directly on Linux, because it comes from &lt;fcntl.h&gt;.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;fcntl.h&gt;</pre><pre>int main(void)<br>{<br>    struct flock lock = { 0 };   /* start with every field at zero */</pre><pre>    lock.l_type   = F_WRLCK;     /* I want a write lock */<br>    lock.l_whence = SEEK_SET;    /* count from the start of the file */<br>    lock.l_start  = 0;           /* begin at byte 0 */<br>    lock.l_len    = 100;         /* lock 100 bytes */</pre><pre>    printf(&quot;type=%d whence=%d start=%ld len=%ld\n&quot;,<br>           lock.l_type, lock.l_whence,<br>           (long)lock.l_start, (long)lock.l_len);</pre><pre>    /* In a real program you would now call:<br>       fcntl(fd, F_SETLK, &amp;lock);<br>       and the kernel reads these same fields. */<br>    return 0;<br>}</pre><p>Output on Linux:</p><pre>type=1 whence=0 start=0 len=100</pre><p>F_WRLCK happens to be 1 and SEEK_SET is 0 on Linux, which is why you see those numbers. The point is that a struct is how your program and the kernel agree on a message. You put values in the fields, and the other side reads the same fields by name.</p><p>The &amp;lock in that comment means &quot;the address of lock&quot;. It has to do with pointers, which we will cover properly a bit later.</p><h3>What comes next</h3><p>We now know how to declare a struct, fill it and read it. You probably noticed that writing struct student every time is a bit long. In the next post we will look at typedef struct, which lets you give your struct a short name, and why the Linux kernel uses it for some types but avoids it for most.</p><p>If you want to practice this with small exercises that check your code as you go, the <a href="https://www.jupiuslearning.com/courses/c-prog-a/">C programming course</a> at Jupius Learning starts from exactly here.</p><h3>Frequently asked questions</h3><h3>How do you initialize a struct in C?</h3><p>You can put the values in braces when you create the variable, in the same order as the fields: struct student s1 = { 1, &quot;Asha&quot;, 87.5f };. You can also start with = { 0 } to set every field to zero, then assign each field with a dot. Any field you leave out of the braces is set to zero.</p><h3>What is the difference between declaring a struct and creating a struct variable?</h3><p>Declaring the struct, like struct student { ... };, only describes its fields. It does not store any data. Creating a variable, like struct student s1;, sets aside memory for one student with its own copy of every field. You declare the type once and can create as many variables of it as you need.</p><h3>What does the dot operator do in C?</h3><p>The dot reads or changes one field of a struct variable. s1.marks gives you the marks field of s1, and s1.marks = 90.0f; changes it. If you have a pointer to a struct instead of the struct itself, you use the arrow -&gt; instead.</p><h3>Can a C struct hold different data types?</h3><p>Yes. That is the main reason structs exist. One struct can mix int, float, char arrays, pointers and even other structs. Our student struct holds an int, a char array and a float side by side.</p><h3>How does the Linux kernel use structs?</h3><p>The Linux kernel uses structs to describe almost everything it manages. Small ones like struct timespec hold a single value, such as the current time. Big ones like task_struct describe a whole running program. The kernel reads and writes their fields with the same dot and arrow operators you use in your own C code.</p><p>Originally published on <a href="https://www.jupiuslearning.com/blog/your-first-c-struct-declare-fill-read-linux-kernel/">Jupius Learning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d19d651bc51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Humble C Struct That Still Runs Billions of Linux Machines]]></title>
            <link>https://medium.com/@vadhernknj19/the-humble-c-struct-that-still-runs-billions-of-linux-machines-3c54b9bf9bf6?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c54b9bf9bf6</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 10:29:27 GMT</pubDate>
            <atom:updated>2026-11-11T10:29:27.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mL3mSx4_nqsZjYQ3.jpg" /></figure><p>Later on we will get to linked lists, queues and trees. But first I want to stop and talk about something smaller. The struct.</p><p>Most beginners meet the struct in C, write one or two small examples, and move on. It feels like a minor feature.</p><p>But this small feature is doing a huge amount of work in the real world. The Linux kernel is written in C, and it is built almost entirely out of structs. And Linux runs on a lot of machines.</p><p>So in this post I will first explain what a struct is, as simply as I can. Then I will show how the Linux kernel uses that same idea to keep real machines running.</p><h3>Where does the Linux kernel run?</h3><p>I want to keep the claims here honest, so I will only use numbers that are easy to check.</p><p>Android phones run on the Linux kernel. Google has said there are more than three billion active Android devices. That covers phones, tablets, TVs and cars.</p><p>Every one of the TOP500 supercomputers has run a Linux based operating system since November 2017. That is still true on the June 2026 list.</p><p>On top of that, Linux is very common on web servers, cloud machines, home routers and all kinds of small embedded boards. I will not throw a precise number at you for those, because the counts vary by survey. But “a lot” is a fair word.</p><p>Now here is the part I find interesting. Inside all of these machines, the kernel keeps track of what is going on using structs. Plain C structs. The same kind you can write in your first week of learning C.</p><h3>What is a C struct?</h3><p>A struct lets you put related pieces of data together under one name.</p><p>Say you want to store a student’s roll number and marks along with the name. You could keep separate variables, but that gets messy fast once you have 50 students. A struct fixes this.</p><pre>/* A tiny beginner example */<br>struct student {<br>    int   roll_no;<br>    char  name[50];<br>    float marks;<br>};</pre><pre>struct student s1 = { 1, &quot;Asha&quot;, 87.5 };<br>printf(&quot;%s scored %.1f\n&quot;, s1.name, s1.marks);</pre><p>That is it. struct student is now a new type, and each variable of that type carries its own copy of the fields. You reach a field with a dot, like s1.name. If you have a pointer to it, you use an arrow, like p-&gt;name.</p><p>A struct can also hold other structs, or pointers to them. That is where things get interesting, and it is exactly what the Linux kernel does all day.</p><h3>task_struct: one kernel struct for every running program</h3><p>When you open an app on your phone, the kernel creates a new process for it. To keep track of that process, it fills in one struct. In the Linux kernel this is called task_struct, also known as the process descriptor.</p><p>Every running program on a Linux machine has one. Your phone right now likely has hundreds of them in memory.</p><p>Here is a very small slice of it. This is simplified. The real struct has a lot more fields.</p><pre>/* Simplified. Only a few of the real fields are shown. */<br>struct task_struct {<br>    volatile long state;          /* running, sleeping, stopped... */<br>    struct mm_struct *mm;         /* this process&#39;s memory */<br>    struct task_struct *parent;   /* who started it */<br>    struct list_head children;    /* its child processes */<br>    struct list_head sibling;     /* its brothers and sisters */<br>    struct list_head tasks;       /* link in the list of all processes */<br>    struct files_struct *files;   /* its open files */<br>};</pre><p>Look at it next to the student struct. It is the same pattern. The difference is that many of these fields are pointers to other structs. The mm field points to a struct about memory. The files field points to a struct about open files. One struct leads to another, and together they describe one running program.</p><p>Some fields are not pointers at all. A field like children is a whole small struct sitting inside the big one. So a struct can hold plain values and pointers, and it can also hold whole structs. That freedom is what lets one type describe something as messy as a running program.</p><h3>Kernel structs that act like objects</h3><p>C does not have classes. But the kernel still gets something very close to objects, using structs full of function pointers.</p><p>When a program opens a file, the kernel creates a file struct for it. One of its fields is f_op, which points to a file_operations struct. That second struct is basically a table of functions.</p><pre>/* Simplified. The real table has many more entries. */<br>struct file_operations {<br>    ssize_t (*read)  (struct file *, char *, size_t, loff_t *);<br>    ssize_t (*write) (struct file *, const char *, size_t, loff_t *);<br>    int     (*open)  (struct inode *, struct file *);<br>    int     (*release)(struct inode *, struct file *);<br>};</pre><pre>struct file {<br>    struct file_operations *f_op;   /* what this file can do */<br>    loff_t f_pos;                   /* where we are in the file */<br>    /* ...many more fields... */<br>};</pre><p>Here is why this matters. A file on a disk, a pipe, and a device all need to be read in very different ways. But the kernel does not care. It just calls file-&gt;f_op-&gt;read(...). Each kind of file fills the table with its own functions. So the same line of code does the right thing for each one.</p><p>If you know a bit of Java or C++, this is the same idea as a method, just built by hand.</p><h3>One more small idea: the kernel’s thread_union</h3><p>The kernel uses a union called thread_union. A union is like a struct, except all its fields share the same memory. In thread_union, a small struct called thread_info and the kernel stack for a process live in the same block of memory. On older 32-bit x86 systems that block was 8 KB. It saves space, and it lets the kernel find thread_info quickly from the stack.</p><h3>A struct is a design tool in the Linux kernel</h3><p>Put all of this together and a pattern shows up. The kernel decides what a thing is, writes one struct for it, and then makes one copy of that struct for every real thing in the machine. One task_struct per program. One file per open file. A device or a mounted disk gets its own struct too.</p><p>That is a way of thinking, not just a C feature. When you learn to design a good struct, you are learning to model the real world in code.</p><h3>Why spend a whole series on it?</h3><p>Because almost everything else in C is built on top of it. Every data structure you will meet later, from a simple list to a tree, is a struct with some extra pointers. If structs feel shaky, those topics will feel shaky too.</p><p>And this is not only for classrooms. It is running inside your phone as you read this, and inside the server that sent you this page. The kernel developers did not need some fancy new tool. They used the plain C struct, very carefully, for decades.</p><p>So I want to slow down here and get comfortable with structs first. Make sure you know when to use the dot and when to use the arrow. Know what it means for a struct to hold a pointer to another struct. Once that feels easy, a lot of C starts to make sense.</p><h3>What comes next</h3><p>In the next few posts we will stay with the struct itself. We will look at how a struct sits in memory, why sizeof sometimes gives a bigger number than you expect, and how structs go inside other structs. After that come unions, bitfields and function pointers inside structs, all with real examples from the Linux kernel.</p><p>Once that ground is solid, we will start a separate series on linked lists, queues and trees.</p><p>If you want to go through all of this step by step with exercises, our <a href="https://www.jupiuslearning.com/courses/c-ds-a">C and Data Structures course</a> at Jupius Learning covers it.</p><p>Originally published on <a href="https://www.jupiuslearning.com/blog/the-humble-c-struct-that-still-runs-billions-of-machines/">Jupius Learning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c54b9bf9bf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Still Need the Basics When AI Writes the Code]]></title>
            <link>https://medium.com/@vadhernknj19/why-you-still-need-the-basics-when-ai-writes-the-code-0e40738cf0a8?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e40738cf0a8</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 08:23:04 GMT</pubDate>
            <atom:updated>2026-11-08T08:23:04.999Z</atom:updated>
            <content:encoded><![CDATA[<p>AI can write code in seconds, but you still have to judge it. Here is why the basics matter more now, and how to learn them.</p><p>Today you can type a sentence into an AI tool and get working code back in a few seconds. A login page, a sorting function, a whole small app. It feels like magic, and honestly it is very useful. I use it too.</p><p>Getting code is easy now. Knowing if that code is any good is still hard. That is where the basics matter.</p><h3>The code runs, so it must be right?</h3><p>Not really. Code can run and still be wrong. The real question is whether it does the right thing for your users, without being slow or unsafe.</p><p>Say you ask for a function to find a user by email. The AI gives you a loop that checks every user one by one. It works fine with 50 users. With 500,000 users your app starts to crawl. If you know a little about data structures, you can spot the trade-off and consider a hash map or a database index. If you don’t, you will just see a slow app and have no idea why.</p><p>The AI did not make a mistake you can see. It made a choice you could not judge.</p><h3>You are now the reviewer</h3><p>When AI writes the code, you still have to check it. Reading code you did not write can be hard. You need to understand its choices, not just its output.</p><p>To review code you need to know:</p><ul><li>What a variable, a loop and a function really do</li><li>How data sits in memory and why that matters</li><li>What a stack, a queue or a tree is good at</li><li>How to read an error message instead of pasting it back and hoping</li></ul><p>Without these, you can only say “it works” or “it doesn’t work”. With them, you can say why.</p><h3>AI is a helping hand, and you decide how far it reaches</h3><p>Think of AI as a helping hand with a huge store of knowledge behind it. It has read more than any person ever could. But a hand does only what the person gives it to do.</p><p>So you can only use AI as well as you understand the problem. If you don’t know what to ask for, you ask for something small and vague, and you get something small and vague back. If you know the topic, you ask sharper questions, and you notice when the answer is off. The AI’s knowledge is always big. Your knowledge is what limits how much of it you can actually use.</p><p>Two people can open the same tool and get very different results. One says “make me a login”. The other says “make a login with hashed passwords, a limit on wrong attempts and a session that expires”. Same AI. The difference is what each person already knows.</p><p>So if you want more from AI, the way to get it is to grow your own knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6gJtLiT9g2vBvpi6.png" /></figure><h3>AI is confident even when it is wrong</h3><p>This can surprise beginners. An AI tool can sound confident when it is wrong. It can invent a function that does not exist. It can use an old method that was removed years ago. It can leave a security hole without warning you.</p><p>You still need to check the answer. The more you understand, the more likely you are to spot a problem.</p><h3>Debugging is where basics pay off</h3><p>Sooner or later the code will break, and it will break in a way the AI cannot fix with one more prompt. Maybe the bug is in how two parts talk to each other. Maybe the data is not what you think it is.</p><p>This is when people who know the fundamentals stay calm. They add a print line, check the value, trace the flow and find the problem. People who skipped the basics paste the error again, get a new guess, paste again, and go in circles for an hour.</p><h3>Interviews still test the basics</h3><p>If you are learning to get a job, this matters a lot. Companies still ask you to explain how a hash table works, or when you would pick a queue over a stack. Some interviews even ask you to code without any AI tool. They want to know that you can think, not only that you can prompt.</p><h3>So how should you use AI?</h3><p>I am not saying avoid it. That would be silly. Here is what works better:</p><ol><li>Learn the basics first, even if it feels slow.</li><li>Try a problem yourself before you ask the AI.</li><li>When the AI gives you code, read every line. Ask it to explain the parts you don’t get.</li><li>Change something small and see what breaks. That is how you really learn.</li></ol><p>Think of AI like a calculator. A calculator did not make maths useless. It just means you can skip the boring sums. But if you don’t understand maths, you won’t even know when the calculator gave you a silly answer.</p><h3>The short version</h3><p>AI has made writing code cheap. It has made understanding code more valuable. The people who do well in the next few years will not be the ones who type the best prompts. They will be the ones who know enough to tell good code from bad code.</p><p>If you want guided practice, you can explore the <a href="https://www.jupiuslearning.com/courses/c-ds-a">C and data structures course at Jupius Learning</a>.</p><p>Originally published on <a href="https://www.jupiuslearning.com/blog/why-you-still-need-the-basics-when-ai-writes-the-code/">Jupius Learning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e40738cf0a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linked Lists Explained with Real Examples from the Linux Kernel]]></title>
            <link>https://medium.com/@vadhernknj19/linked-lists-explained-with-real-examples-from-the-linux-kernel-e62239f29301?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e62239f29301</guid>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 14:37:22 GMT</pubDate>
            <atom:updated>2026-11-06T14:37:22.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*88J-7lbzmM1d5utD.png" /></figure><p>In the last post on queues, linked lists kept showing up. Wait queues were built from one, and the runqueue was 140 of them. This time we look at the linked list properly. It is one of the most used structures in the Linux kernel.</p><p>Let’s write a small one in C first, then see how the kernel does it.</p><h3>What is a linked list?</h3><p>Think of a treasure hunt. Each clue tells you where the next one is. You can’t jump to clue five. You start at the first and follow the chain.</p><p>A linked list works the same way. It is a chain of nodes. Each node holds some data and a pointer to the next node. The last one points to NULL.</p><p>There are two common kinds:</p><ul><li>In a <strong>singly linked list</strong>, each node points only to the next one</li><li>In a <strong>doubly linked list</strong>, each node points to the next one and the one before it</li></ul><p>The good part is that adding or removing a node is cheap once you are at the right spot. You change a pointer or two and nothing moves. In an array, adding in the middle means shifting everything after it.</p><p>The bad part is search. There is no index, so to find 42 you walk from the start and check each node.</p><h3>A tiny linked list in C</h3><p>Here is a small singly linked list of integers.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;</pre><pre>struct node {<br>    int data;<br>    struct node *next;<br>};</pre><pre>struct node *head = NULL;     /* NULL means the list is empty */</pre><pre>void push_front(int x) {<br>    struct node *n = malloc(sizeof *n);<br>    if (!n) return;           /* out of memory, so we stop */<br>    n-&gt;data = x;<br>    n-&gt;next = head;           /* new node points to the old first node */<br>    head = n;                 /* and becomes the new first node */<br>}</pre><pre>void delete_value(int x) {<br>    struct node **pp = &amp;head;<br>    while (*pp &amp;&amp; (*pp)-&gt;data != x)<br>        pp = &amp;(*pp)-&gt;next;    /* walk until we find x */<br>    if (*pp) {<br>        struct node *gone = *pp;<br>        *pp = gone-&gt;next;     /* skip over the node */<br>        free(gone);<br>    }<br>}</pre><pre>void print_list(void) {<br>    for (struct node *p = head; p; p = p-&gt;next)<br>        printf(&quot;%d -&gt; &quot;, p-&gt;data);<br>    printf(&quot;NULL\n&quot;);<br>}</pre><p>Adding at the front takes the same short time no matter how long the list is. We make one node, change two pointers, and never look at the rest. That is why it is O(1).</p><p>Deleting by value has to walk first, so it gets slower as the list grows. The pointer to a pointer, pp, lets the same code remove the first node or a middle one.</p><h3>Doubly linked lists and the kernel’s list_head</h3><p>A doubly linked list adds a prev pointer to each node. It costs a bit more memory, but you can walk both ways and remove a node without hunting for the one before it.</p><p>The Linux kernel uses doubly linked lists everywhere, but it does not write a new list for each kind of data. It has one generic struct called list_head with only two fields, next and prev. No data at all.</p><p>The trick is that you put a list_head inside your own struct. The list does not hold your data. Your data holds the list.</p><p>A few things follow from this:</p><ul><li>The lists are circular. An empty list is just a head whose next and prev both point back to itself.</li><li>The pointers point to other list_head fields, not to the start of the bigger struct. So when you are at a node, you need a way to get back to the struct around it.</li><li>The kernel helper list_entry does that. It knows how far the list_head field sits from the start of the struct and subtracts that distance from the pointer. This idea is usually called &quot;container of&quot;.</li><li>Because every list looks the same, the kernel needs only one set of helpers to add, delete, and walk. Every subsystem reuses them instead of writing its own.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6lam-2pcCQIHX1JL.png" /></figure><h3>Where the Linux kernel uses linked lists</h3><p>The examples below are from the Linux 2.6 kernel. Newer kernels have changed some details, but the ideas are still there.</p><h3>The process list</h3><p>Every process is linked into one big list through a list_head field called tasks in its descriptor. The head is init_task, the descriptor of the very first process.</p><p>To visit every process, the kernel has a macro called for_each_process. It starts at init_task, follows next, and stops when it comes back around. That stop rule works because the list is circular.</p><h3>The runqueue</h3><p>In Linux 2.6 each CPU has 140 lists, one per priority, and each is a plain list_head list. When a process becomes ready, enqueue_task() adds it to the tail of the list for its priority. To pick the next process, the scheduler finds the first non-empty list and takes the node at its front, using list_entry to get back the process.</p><h3>Wait queues</h3><p>Wait queues are also built on list_head. Each sleeper is a small entry in the list, and the head carries a lock. Exclusive sleepers go at the tail so the kernel can wake just one. Adding at the tail is cheap because the head&#39;s prev points straight at the last entry.</p><h3>Hash tables and hlist</h3><p>Hash tables have many buckets, and most are empty or short. A two-pointer head for each would waste memory. So the kernel has a lighter hlist. Its head, hlist_head, is a single pointer, and the list is not circular. You lose quick access to the tail, which a bucket rarely needs. The PID lookup table uses it.</p><h3>Everyday uses</h3><p>You meet linked lists outside the kernel too:</p><ul><li>A music playlist where “next” and “previous” move you along a chain</li><li>Undo history in an editor, where each change points back to the one before</li><li>Browser back and forward history, which behaves like a doubly linked chain</li><li>Free block lists in memory allocators, where each free block points to the next free one</li></ul><h3>List or array?</h3><p>Use an array when you read by position a lot, like “give me item 500”. An array gets there in one step, and its items sit together in memory, which makes walking fast on real hardware.</p><p>Use a linked list when you add and remove items often, especially in the middle or at the front, and you already have a pointer to the spot. A list grows one node at a time, so you never guess a size up front. The price is extra memory for pointers and slow search.</p><h3>Try it yourself</h3><ol><li>Add a push_back() function to the code above. Then keep a tail pointer so it runs in O(1).</li><li>Write a function that reverses the list in place, by changing pointers only.</li><li>Change the list to a doubly linked one, and write a delete that takes a node pointer instead of a value.</li></ol><h3>What comes next</h3><p>Next in the series is the hash table. The hlist we just saw will make more sense once we look at how buckets work.</p><p>The best way to learn a linked list is to write one and then break it on purpose. Draw the boxes and arrows on paper before each pointer change, and step through it in a debugger. If you want a guided path, the <a href="https://www.jupiuslearning.com/courses/c-ds-a/">C and data structures course</a> at Jupius Learning goes through these one step at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e62239f29301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Learn Zephyr RTOS on Real Hardware: A 24 Week Plan]]></title>
            <link>https://medium.com/@vadhernknj19/how-to-learn-zephyr-rtos-on-real-hardware-a-24-week-plan-894b68b93012?source=rss-56ff44f2eb9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/894b68b93012</guid>
            <category><![CDATA[esp32-s3]]></category>
            <category><![CDATA[zephyr]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[edtech]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Vadher Nikunj]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 06:10:00 GMT</pubDate>
            <atom:updated>2026-11-04T06:10:00.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dh8bnnOX8jEztW1V.png" /></figure><p>In the last post we looked at what Zephyr is and wrote a small program with two threads and a message queue. A common next question is: how do I actually learn this properly? Zephyr is big. There are hundreds of boards, a build tool, Devicetree, Kconfig and a long list of subsystems. It is easy to jump around and end up knowing a little of everything and not much of anything.</p><p>So in this post we share a plan for learning Zephyr on a real board over about 24 weeks. You can follow it on your own with any board Zephyr supports. We use the ESP32-S3-DevKitC-1 with Zephyr 4.1 and the west tool.</p><h3>What to know in C first</h3><p>Zephyr code is full of pointers, structs and macros. If those still feel shaky, fix that first. You will not get far reading Zephyr samples otherwise.</p><p>Before you start, you should be able to:</p><ul><li>pass a pointer to a struct into a function and change it there</li><li>read a macro and work out what it expands to</li><li>use static, const and volatile and say why each one is there</li><li>split code across .c and .h files</li></ul><p>Some earlier embedded work, like blinking an LED with a vendor SDK, helps. It is not a must.</p><h3>Stage 1: the build system and kernel objects</h3><p>Start with the tools. Install Zephyr and west, build a sample, flash it, and print Hello World over the serial port. This sounds small, but many people lose days here later because they skipped it. Learn what west build and west flash do, and where the build output goes.</p><p>Then go through the kernel objects one at a time:</p><ul><li>threads and sleep</li><li>semaphores</li><li>mutexes and condition variables</li><li>message queues</li><li>software timers and work queues</li></ul><p>For each one, write a tiny program that only uses that object. Make two threads fight over a shared counter, then fix it with a mutex. Make one thread wait on a semaphore that another gives. These small tests teach you more than reading the API docs.</p><p>In our plan this stage covers Units 1 to 8, roughly the first third.</p><h3>Stage 2: memory, Devicetree and real hardware</h3><p>Next comes memory. Learn how Zephyr gives you heaps and fixed blocks, and why many embedded programs avoid malloc at run time.</p><p>Then spend real time on Devicetree and Kconfig. This is where most beginners get stuck. Devicetree describes the hardware: which pins, which buses, which sensors. Kconfig turns features on and off. Learn to write an overlay file for your board and use aliases so your code does not hard code pin numbers.</p><p>Once that clicks, drive real parts: GPIO, PWM, an I2C sensor, and flash storage (NVS) for something simple like a boot counter that survives a reset. In our plan this is Units 9 to 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*tPEYXTea2PfAqyDi.png" /></figure><h3>Stage 3: services, networking and updates</h3><p>The last stage is about the things real firmware needs around the core logic:</p><ul><li>logging modules, so you can turn debug output up or down per part of the code</li><li>the Zephyr shell, so you can type commands to your board over serial</li><li>zbus, for passing data between parts of your program</li><li>Wi-Fi as a station, and a small web page from a soft access point</li><li>over the air updates (OTA)</li></ul><p>We also drive a stepper motor in this stage, because it forces you to care about timing.</p><p>End with a capstone. Do not add a new topic. Take three things you already built and make them run together in one firmware. This is harder than it sounds. You have to bring things up in the right order and stop one part from breaking another. That is very close to real product work.</p><h3>Why a real board beats a simulator</h3><p>Simulators and copy paste tutorials are fine for a first look. But they hide the problems you will meet on the job: wrong wiring, a sensor at the wrong I2C address, a stack that is too small, a thread that never wakes up.</p><p>A simple habit helps a lot. For every lab, make your firmware print one short, fixed line over serial when the task really worked. For example SEM:OK for a semaphore lab, DTS:OK for a Devicetree lab, or OTA:OK after an update. If the line does not show up, the lab is not done. No guessing, no &quot;it probably works&quot;. This also makes it easy to check your work with a script later.</p><h3>How to check your own progress</h3><p>Write down a few outcomes for yourself, one per area. For example: “I can use kernel objects to share data safely between threads” or “I can add a new I2C sensor using only an overlay and a driver”. Then, at the end of each stage, ask if you can do each one from a blank project without looking at old code. If not, go back before moving on.</p><p>Short quizzes after each topic help too. They show gaps fast.</p><h3>Common mistakes</h3><ul><li>skipping C basics and fighting syntax instead of learning Zephyr</li><li>jumping to Wi-Fi or OTA before understanding threads and queues</li><li>copying a Devicetree overlay without knowing what each line means</li><li>printing from many threads with no logging setup, and then not being able to read the output</li><li>testing features one by one but never together</li></ul><h3>The plan we use</h3><p>This is the plan we follow in our 24 week course, Zephyr RTOS on ESP32-S3. If you want to see the full list of units and outcomes, it is on the <a href="https://www.jupiuslearning.com/courses/zep-rtos-a/">course page</a>. Either way, the order above works well on your own too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=894b68b93012" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>