{"version":"https://jsonfeed.org/version/1.1","title":"SystemCoding","home_page_url":"https://systemcoding.dev","feed_url":"https://systemcoding.dev/feed.json","description":"Practical coding tutorials and techniques for hardware and computer systems.","language":"en","authors":[{"name":"SystemCoding","url":"https://systemcoding.dev"}],"items":[{"id":"https://systemcoding.dev/snippets/ignore-sigpipe-process-wide-with-signal-sigpipe-sig-ign","url":"https://systemcoding.dev/snippets/ignore-sigpipe-process-wide-with-signal-sigpipe-sig-ign","title":"Ignore SIGPIPE process-wide with signal(SIGPIPE, SIG_IGN)","summary":"Writing to a closed pipe or socket kills the process with SIGPIPE. Ignore the signal and write(2) returns -1 with EPIPE, which you can handle in the code.","content_html":"<p>A server that writes to a client which has already hung up gets killed, silently, by <code>SIGPIPE</code>, whose default action is to terminate. For a program that handles many connections you want the error instead. Setting the disposition to <code>SIG_IGN</code> makes the write fail with <code>EPIPE</code>, as described in <a href=\"https://man7.org/linux/man-pages/man7/signal.7.html\">signal(7)</a>.</p>\n<pre data-filename=\"sigpipe.c\"><code class=\"language-c\">#include &lt;errno.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;unistd.h&gt;\n\nint main(void) {\n    signal(SIGPIPE, SIG_IGN);\n\n    int fds[2];\n    if (pipe(fds) &lt; 0) { perror(\"pipe\"); return 1; }\n    close(fds[0]);                         /* no reader any more */\n\n    if (write(fds[1], \"x\", 1) &lt; 0)\n        printf(\"write: %s\\n\", strerror(errno));\n    return 0;\n}</code></pre>\n<pre><code class=\"language-text\">write: Broken pipe</code></pre>\n<p>Without the <code>signal</code> line the process dies at the <code>write</code>, with no output, and the shell reports it as exit status 141, which is 128 plus the signal number 13. The setting is process-wide and inherited across <code>exec</code>, so a program you start with <code>SIGPIPE</code> ignored keeps it ignored unless it resets it. That is why a command run in a shell pipeline and one run from a script can behave differently.</p>\n<p>The blunt setting hides pipe errors in a command-line filter that should stop when its output closes, such as the left side of <code>| head</code>, so apply it in servers and not in simple tools. For a single socket you can leave the disposition alone and pass <code>MSG_NOSIGNAL</code> to <code>send</code>, which suppresses the signal for that call only. In a library, prefer that over changing a global setting that belongs to the application.</p>","date_published":"2026-11-24T00:55:56+00:00","tags":["Systems Programming"]},{"id":"https://systemcoding.dev/snippets/turn-on-runtime-subscript-checks-with-ssrange","url":"https://systemcoding.dev/snippets/turn-on-runtime-subscript-checks-with-ssrange","title":"Turn on runtime subscript checks with SSRANGE","summary":"Turn on runtime subscript checks with the SSRANGE compiler option, so a bad index stops the run with a message.","content_html":"<p>By default Enterprise COBOL for z/OS 6.4 does not check table subscripts, so a subscript past the end of a table reads or overwrites the storage after it. The <code>SSRANGE</code> compiler option adds a check to every reference.</p>\n<pre><code class=\"language-cobol\">CBL SSRANGE\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. RANGECHK.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  WS-TAB.\n           05  WS-ENTRY   PIC 9 OCCURS 3 TIMES.\n       01  WS-I           PIC 9 VALUE 4.\n       PROCEDURE DIVISION.\n           MOVE 1 TO WS-ENTRY (WS-I)\n           STOP RUN.</code></pre>\n<pre><code class=\"language-text\">IGZ0006S The reference to table WS-ENTRY by verb number 1 on line 10 addressed an area outside the region of the table.</code></pre>\n<p>The table has three entries and the subscript is 4, so the check fails and the run ends with this message and a Language Environment abend. The line number is the source line of the <code>MOVE</code> in this listing, and yours will differ.</p>\n<p>The check also needs the runtime option <code>CHECK(ON)</code>, which is the default, so a site that sets <code>CHECK(OFF)</code> loses it. Every checked reference costs extra instructions, so many shops compile with <code>SSRANGE</code> in test and without it in production. It does not check reference modification unless the same option is on, and then it applies to those too.</p>","date_published":"2026-11-24T00:55:36+00:00","tags":["Mainframe"]},{"id":"https://systemcoding.dev/snippets/centre-align-stm32-pwm-with-the-tim-cms-bits","url":"https://systemcoding.dev/snippets/centre-align-stm32-pwm-with-the-tim-cms-bits","title":"Centre-align STM32 PWM with the TIM CMS bits","summary":"Centre-align STM32 PWM with the CMS bits in TIMx_CR1, which counts up and down and halves the PWM frequency for the same reload value.","content_html":"<p>In edge-aligned mode, the counter counts up and the output goes high at the start of every period. In centre-aligned mode, it counts up and then down, so the pulse is symmetrical around the middle of the period. That is what a motor driver or a class-D stage wants, because the switching edges spread out and the average current ripple is smaller.</p>\n<pre><code class=\"language-c\">// STM32F4 timer 1, stopped, with PSC and ARR already set\nTIM1-&gt;CR1 = (TIM1-&gt;CR1 &amp; ~TIM_CR1_CMS) | TIM_CR1_CMS_0;   // centre-aligned mode 1\nTIM1-&gt;CCR1 = TIM1-&gt;ARR / 4;\nTIM1-&gt;CCMR1 |= (6U &lt;&lt; TIM_CCMR1_OC1M_Pos);                // PWM mode 1\nTIM1-&gt;CCER  |= TIM_CCER_CC1E;\nTIM1-&gt;BDTR  |= TIM_BDTR_MOE;\nTIM1-&gt;CR1   |= TIM_CR1_CEN;</code></pre>\n<p><code>CMS</code> has three settings: <code>01</code>, <code>10</code> and <code>11</code> differ only in when the compare interrupt flag is set (counting down, up or both). The PWM waveform is the same for all three, so mode 1 is usually enough.</p>\n<p>Two things catch people. The reference manual forbids switching from edge-aligned to centre-aligned while the counter is running, so configure <code>CMS</code> with <code>CEN</code> clear, as above. And the period doubles: the counter travels up to <code>ARR</code> and back, so the frequency is <code>f_timer / (2 × ARR × (PSC + 1))</code>, half of the edge-aligned value for the same registers.</p>\n<p>With the HAL, set <code>htim.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED1</code> before <code>HAL_TIM_PWM_Init</code>. The register description is in RM0090.</p>","date_published":"2026-11-24T00:55:16+00:00","tags":["Embedded"]},{"id":"https://systemcoding.dev/snippets/check-malloc-s-return-value-and-handle-allocation-failure","url":"https://systemcoding.dev/snippets/check-malloc-s-return-value-and-handle-allocation-failure","title":"Check malloc's return value and handle allocation failure","summary":"malloc(3) returns NULL and sets ENOMEM when it cannot allocate. Test it before use, and know that Linux overcommit often kills the process instead of failing.","content_html":"<p>The rule is old and still ignored: <code>malloc</code> can return <code>NULL</code>, and writing through that pointer is undefined behaviour. The cleanest way to see the failure path is to make allocation fail on purpose. A cap on address space with <code>setrlimit(RLIMIT_AS)</code> does it without exhausting the machine.</p>\n<pre data-filename=\"oom.c\"><code class=\"language-c\">#include &lt;errno.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys/resource.h&gt;\n\nint main(void) {\n    struct rlimit lim = { .rlim_cur = 256UL &lt;&lt; 20, .rlim_max = 256UL &lt;&lt; 20 };\n    if (setrlimit(RLIMIT_AS, &amp;lim) &lt; 0) { perror(\"setrlimit\"); return 1; }\n\n    char *big = malloc(1UL &lt;&lt; 30);                  /* 1 GiB */\n    if (big == NULL) {\n        fprintf(stderr, \"malloc failed: %s\\n\", strerror(errno));\n        return 1;\n    }\n    big[0] = 1;\n    free(big);\n    return 0;\n}</code></pre>\n<pre><code class=\"language-text\">malloc failed: Cannot allocate memory</code></pre>\n<p>On Linux, with the default overcommit heuristic, a large request usually succeeds and the failure shows up later: the OOM killer ends a process when pages are touched and RAM runs out. Only a hard limit like <code>RLIMIT_AS</code>, a container memory cap on address space, or <code>vm.overcommit_memory=2</code> makes <code>malloc</code> itself return <code>NULL</code>. That is why the check is still needed. It guards embedded targets, servers with limits set, and 32-bit builds, and it costs one branch.</p>\n<p><a href=\"https://man7.org/linux/man-pages/man3/malloc.3.html\">malloc(3)</a> sets <code>errno</code> to <code>ENOMEM</code>. Decide what failure means before you write the call: return an error to the caller, free what was built so far, or abort in a main program with a clear message. <code>malloc(0)</code> may return <code>NULL</code> or a unique pointer, so do not use <code>NULL</code> alone as the failure signal when the size can be zero.</p>","date_published":"2026-11-24T00:54:56+00:00","tags":["Systems Programming"]},{"id":"https://systemcoding.dev/snippets/copy-a-sequential-dataset-with-iebgener-sysut1-and-sysut2","url":"https://systemcoding.dev/snippets/copy-a-sequential-dataset-with-iebgener-sysut1-and-sysut2","title":"Copy a sequential dataset with IEBGENER SYSUT1 and SYSUT2","summary":"Copy one sequential data set to another with IEBGENER, using SYSUT1 as input, SYSUT2 as output and a dummy SYSIN, on z/OS 3.1.","content_html":"<p><code>IEBGENER</code> copies records from one sequential data set to another, and it is the standard answer to \"copy this file in a job\".</p>\n<pre><code class=\"language-jcl\">//COPY     EXEC PGM=IEBGENER\n//SYSPRINT DD SYSOUT=*\n//SYSIN    DD DUMMY\n//SYSUT1   DD DISP=SHR,DSN=USER1.PAY.DATA\n//SYSUT2   DD DSN=USER1.PAY.COPY,DISP=(NEW,CATLG,DELETE),\n//         LIKE=USER1.PAY.DATA</code></pre>\n<pre><code class=\"language-text\">IEB147I END OF JOB - 0 WAS HIGHEST SEVERITY CODE</code></pre>\n<p><code>SYSUT1</code> is the input and <code>SYSUT2</code> the output. <code>SYSIN DD DUMMY</code> tells the program there are no control statements, so it copies everything unchanged, and <code>SYSPRINT</code> takes its messages. <code>LIKE=</code> gives the new file the same attributes and space as the original, which saves writing a <code>DCB</code> and <code>SPACE</code>.</p>\n<p>The program fails with <code>IEB...</code> messages and a return code of 12 when the output has a record length that is too small for the input, so make sure that the two agree. On a system with DFSORT, <code>IEBGENER</code> is usually replaced by <code>ICEGENER</code>, which has the same interface and is faster, and your site may map the name for you.</p>\n<p>It copies sequential data sets and members, not whole libraries. For a partitioned data set, use <code>IEBCOPY</code> from the next topics.</p>","date_published":"2026-11-24T00:54:36+00:00","tags":["Mainframe"]},{"id":"https://systemcoding.dev/snippets/read-one-adc-channel-with-hal-adc-start-and-hal-adc-pollforconversion","url":"https://systemcoding.dev/snippets/read-one-adc-channel-with-hal-adc-start-and-hal-adc-pollforconversion","title":"Read one ADC channel with HAL_ADC_Start and HAL_ADC_PollForConversion","summary":"Read one STM32 ADC channel in polling mode with HAL_ADC_Start, HAL_ADC_PollForConversion and HAL_ADC_GetValue, and convert the result to millivolts.","content_html":"<p>For a single slow reading, polling is the least code. You start the conversion, wait for the end-of-conversion flag and read the data register. With the STM32F4 HAL and the ADC set to 12 bits, a 3.3 V reference gives 0 to 4095.</p>\n<pre><code class=\"language-c\">uint32_t adc_read_mv(void)\n{\n    HAL_ADC_Start(&amp;hadc1);\n    if (HAL_ADC_PollForConversion(&amp;hadc1, 10) != HAL_OK) {\n        HAL_ADC_Stop(&amp;hadc1);\n        return 0;\n    }\n    uint32_t raw = HAL_ADC_GetValue(&amp;hadc1);\n    HAL_ADC_Stop(&amp;hadc1);\n\n    printf(\"raw=%lu\\n\", raw);\n    return (raw * 3300U) / 4095U;\n}</code></pre>\n<p>With the input at mid-supply the print shows the raw count and the function returns about 1650 millivolts:</p>\n<pre><code class=\"language-text\">raw=2048</code></pre>\n<p>The 10 is a timeout in milliseconds. If <code>HAL_ADC_PollForConversion</code> returns <code>HAL_TIMEOUT</code> the ADC is not running, often because the clock for the peripheral was not enabled or the channel was never configured.</p>\n<p>Check the <code>EOCSelection</code> field in the ADC init. With <code>ADC_EOC_SEQ_CONV</code> the flag is raised only at the end of the whole sequence, so a multi-channel scan seems to finish early or return only the last channel. For a scan, use <code>ADC_EOC_SINGLE_CONV</code>, or switch to DMA.</p>\n<p>Stopping after each read is not required in continuous mode but keeps single-shot code predictable. The functions are in <code>stm32f4xx_hal_adc.c</code>.</p>","date_published":"2026-11-24T00:54:16+00:00","tags":["Embedded"]},{"id":"https://systemcoding.dev/snippets/get-the-page-size-with-sysconf-sc-pagesize","url":"https://systemcoding.dev/snippets/get-the-page-size-with-sysconf-sc-pagesize","title":"Get the page size with sysconf(_SC_PAGESIZE)","summary":"Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.","content_html":"<p>Every <code>mmap</code> length, alignment and <code>madvise</code> range is measured in pages, so a program needs the page size. The portable call is <a href=\"https://man7.org/linux/man-pages/man3/sysconf.3.html\">sysconf(3)</a> with <code>_SC_PAGESIZE</code>. It returns a <code>long</code>, and on failure -1.</p>\n<pre data-filename=\"pagesize.c\"><code class=\"language-c\">#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n\nint main(void) {\n    long page = sysconf(_SC_PAGESIZE);\n    if (page &lt; 0) {\n        perror(\"sysconf\");\n        return 1;\n    }\n    printf(\"page size: %ld\\n\", page);\n    return 0;\n}</code></pre>\n<pre><code class=\"language-text\">page size: 4096</code></pre>\n<p>That is the result on x86-64. The number is not a constant of the architecture. An arm64 Linux kernel can be built for 4 KiB, 16 KiB or 64 KiB pages, and some distributions ship the larger sizes, so code that hard-codes 4096 passes on a laptop and fails with <code>EINVAL</code> from <code>munmap</code> or <code>mmap</code> on that kernel. The kernel passes the value to user space in the auxiliary vector (<code>AT_PAGESZ</code>), and glibc reads it from there, so the call costs no system call.</p>\n<p>Cache the result in a static if you use it often, and compute masks from it, as in <code>page - 1</code>, rather than from a literal. Avoid <code>getpagesize</code>, which POSIX marked obsolescent in 2001 and removed in POSIX.1-2008. <code>PAGE_SIZE</code> from <code>&lt;sys/user.h&gt;</code> or <code>&lt;asm/page.h&gt;</code> is a build-time constant and has the same problem.</p>","date_published":"2026-11-24T00:53:56+00:00","tags":["Systems Programming"]},{"id":"https://systemcoding.dev/snippets/create-a-read-only-seq-file-in-one-line-with-define-show-attribute","url":"https://systemcoding.dev/snippets/create-a-read-only-seq-file-in-one-line-with-define-show-attribute","title":"Create a read-only seq_file in one line with DEFINE_SHOW_ATTRIBUTE","summary":"Turn one show function into a complete read-only debugfs file with DEFINE_SHOW_ATTRIBUTE() in Linux 6.12, with no hand-written file_operations.","content_html":"<p>Most read-only status files need the same five lines of <code>file_operations</code> boilerplate: <code>open</code>, <code>read</code>, <code>llseek</code>, <code>release</code>. <code>DEFINE_SHOW_ATTRIBUTE(name)</code> generates all of it from a single <code>name_show()</code> function, so a whole file is the show function plus one line. The macro lives in <code>linux/seq_file.h</code> and works in Linux 6.12.</p>\n<pre data-filename=\"hello.c\"><code class=\"language-c\">#include &lt;linux/debugfs.h&gt;\n#include &lt;linux/module.h&gt;\n#include &lt;linux/seq_file.h&gt;\n\nstatic int hello_show(struct seq_file *m, void *v)\n{\n\tseq_printf(m, \"boards: %d\\n\", 3);\n\treturn 0;\n}\nDEFINE_SHOW_ATTRIBUTE(hello);\n\nstatic struct dentry *file;\n\nstatic int __init hello_init(void)\n{\n\tfile = debugfs_create_file(\"hello\", 0444, NULL, NULL, &amp;hello_fops);\n\treturn 0;\n}\n\nstatic void __exit hello_exit(void)\n{\n\tdebugfs_remove(file);\n}\n\nmodule_init(hello_init);\nmodule_exit(hello_exit);\nMODULE_LICENSE(\"GPL\");</code></pre>\n<pre><code class=\"language-text\">boards: 3</code></pre>\n<p>The macro pastes the name you give it onto three symbols: it expects <code>hello_show()</code>, and it defines <code>hello_open()</code> and <code>hello_fops</code>. The fourth argument of <code>debugfs_create_file()</code> arrives as <code>m-&gt;private</code> inside the show function, because the generated open passes <code>inode-&gt;i_private</code> to <code>single_open()</code>.</p>\n<p>The catch is <code>/proc</code>. Since Linux 5.6, <code>proc_create()</code> takes a <code>struct proc_ops</code>, not a <code>file_operations</code>, so this macro does not fit there. Use <code>DEFINE_PROC_SHOW_ATTRIBUTE(name)</code>, which generates <code>name_proc_ops</code>, or skip the macro with <code>proc_create_single()</code>. The seq_file model is described in <a href=\"https://docs.kernel.org/filesystems/seq_file.html\">the kernel docs</a>.</p>","date_published":"2026-11-24T00:53:36+00:00","tags":["Kernels"]},{"id":"https://systemcoding.dev/snippets/write-a-job-card-with-class-msgclass-and-notify-and-sysuid","url":"https://systemcoding.dev/snippets/write-a-job-card-with-class-msgclass-and-notify-and-sysuid","title":"Write a JOB card with CLASS, MSGCLASS and NOTIFY=&SYSUID","summary":"Write a minimal JOB card with an accounting field, CLASS, MSGCLASS and NOTIFY=&SYSUID, so JES2 on z/OS 3.1 messages you when the job ends.","content_html":"<p>A job starts with a <code>JOB</code> card, and four things on it matter in practice: where the job runs, where its output goes, and who gets told.</p>\n<pre><code class=\"language-jcl\">//PAYJOB   JOB (ACCT1),'PAYROLL RUN',CLASS=A,MSGCLASS=H,\n//         NOTIFY=&amp;SYSUID\n//STEP1    EXEC PGM=IEFBR14</code></pre>\n<pre><code class=\"language-text\">JOB PAYJOB(JOB01234) SUBMITTED\n$HASP165 PAYJOB ENDED AT N1 MAXCC=0000 CN(INTERNAL)</code></pre>\n<p><code>CLASS=A</code> picks the job class, which decides which initiators may run it, and your installation defines what each letter means. <code>MSGCLASS=H</code> sends the job log and system messages to output class <code>H</code>, commonly a held class, so the output waits on the spool for you to read. <code>NOTIFY=&amp;SYSUID</code> is a system symbol that JES2 on z/OS 3.1 replaces with the user ID that submitted the job, so the same card works for everyone and the end message goes to whoever submitted it.</p>\n<p>The text in parentheses is the accounting information, and the quoted text is the programmer name. Both are installation rules, so copy the format your site uses. The class letters and the held message class above are examples, not defaults.</p>","date_published":"2026-11-24T00:53:16+00:00","tags":["Mainframe"]},{"id":"https://systemcoding.dev/snippets/define-a-usb-device-descriptor-in-tud-descriptor-device-cb","url":"https://systemcoding.dev/snippets/define-a-usb-device-descriptor-in-tud-descriptor-device-cb","title":"Define a USB device descriptor in tud_descriptor_device_cb","summary":"Return a TinyUSB device descriptor from tud_descriptor_device_cb with a static tusb_desc_device_t, using the IAD class codes a composite CDC device needs.","content_html":"<p>TinyUSB asks your firmware for the device descriptor when the host enumerates it, by calling <code>tud_descriptor_device_cb</code>. You return a pointer to a <code>tusb_desc_device_t</code>, and that memory has to outlive the call.</p>\n<pre><code class=\"language-c\">#include \"tusb.h\"\n\nstatic tusb_desc_device_t const desc_device = {\n    .bLength            = sizeof(tusb_desc_device_t),\n    .bDescriptorType    = TUSB_DESC_DEVICE,\n    .bcdUSB             = 0x0200,\n    .bDeviceClass       = TUSB_CLASS_MISC,\n    .bDeviceSubClass    = MISC_SUBCLASS_COMMON,\n    .bDeviceProtocol    = MISC_PROTOCOL_IAD,\n    .bMaxPacketSize0    = CFG_TUD_ENDPOINT0_SIZE,\n    .idVendor           = 0xCafe,\n    .idProduct          = 0x4001,\n    .bcdDevice          = 0x0100,\n    .iManufacturer      = 0x01,\n    .iProduct           = 0x02,\n    .iSerialNumber      = 0x03,\n    .bNumConfigurations = 0x01,\n};\n\nuint8_t const *tud_descriptor_device_cb(void)\n{\n    return (uint8_t const *)&amp;desc_device;\n}</code></pre>\n<p>On Linux the device shows up in <code>lsusb</code> with the IDs from the descriptor:</p>\n<pre><code class=\"language-text\">Bus 001 Device 012: ID cafe:4001 TinyUSB Example</code></pre>\n<p>The class triple <code>0xEF</code>, <code>0x02</code>, <code>0x01</code> (<code>TUSB_CLASS_MISC</code>, common subclass, IAD protocol) tells the host that interfaces are grouped by interface association descriptors. A CDC serial port is two interfaces, and without this triple Windows may load the wrong driver for it. A single-interface device can use class <code>0</code>.</p>\n<p><code>0xCafe</code> is the vendor ID of the TinyUSB examples, not one you may ship with. Use your own vendor ID or a product ID from a free allocation such as pid.codes. The code follows TinyUSB 0.18.</p>","date_published":"2026-11-24T00:52:56+00:00","tags":["Embedded"]},{"id":"https://systemcoding.dev/snippets/detach-from-the-controlling-terminal-with-setsid-after-fork","url":"https://systemcoding.dev/snippets/detach-from-the-controlling-terminal-with-setsid-after-fork","title":"Detach from the controlling terminal with setsid after fork","summary":"Detach a daemon from its terminal by forking, exiting the parent and calling setsid in the child on Linux 6.12, so closing the terminal cannot hang it up.","content_html":"<p>A program started from a shell belongs to the shell's session and process group, and its controlling terminal sends it <code>SIGHUP</code> when the terminal closes. A daemon must leave all of that. <code>setsid</code> creates a new session with the caller as leader and no controlling terminal, but it fails with <code>EPERM</code> for a process group leader, which a freshly started program often is. The fix is to fork first: the child is never a group leader, so the call succeeds.</p>\n<pre data-filename=\"detach.c\"><code class=\"language-c\">#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n\nint main(void) {\n    pid_t pid = fork();\n    if (pid &lt; 0) { perror(\"fork\"); return 1; }\n    if (pid &gt; 0) {\n        printf(\"daemon pid %d\\n\", (int)pid);\n        _exit(0);\n    }\n\n    if (setsid() &lt; 0) { perror(\"setsid\"); _exit(1); }\n\n    sleep(60);\n    return 0;\n}</code></pre>\n<pre><code class=\"language-bash\">./detach\nps -o pid,ppid,sid,tty,comm -C detach</code></pre>\n<pre><code class=\"language-text\">daemon pid 4210\n    PID    PPID     SID TT       COMMAND\n   4210       1    4210 ?        detach</code></pre>\n<p>The session id equals the pid, which is what a session leader looks like, and <code>TT</code> is <code>?</code> for no terminal. The parent exited, so the kernel re-parented the child to pid 1 (or the nearest subreaper).</p>\n<p>The parent calls <code>_exit</code>, not <code>exit</code>, so buffered output inherited from the parent is not flushed twice. Per [<code>setsid(2)</code>](https://man7.org/linux/man-pages/man2/setsid.2.html), the new leader may still acquire a controlling terminal by opening a terminal device without <code>O_NOCTTY</code>, which the classic double-fork guards against with a second fork. If you run under systemd, you need none of this: a plain foreground process with <code>Type=simple</code> is the supported way.</p>","date_published":"2026-11-24T00:52:36+00:00","tags":["Systems Programming"]},{"id":"https://systemcoding.dev/snippets/clear-a-vector-register-with-vpxor-ymm0-ymm0-ymm0","url":"https://systemcoding.dev/snippets/clear-a-vector-register-with-vpxor-ymm0-ymm0-ymm0","title":"Clear a vector register with vpxor ymm0, ymm0, ymm0","summary":"Zero a 256-bit register with vpxor ymm0, ymm0, ymm0, which needs AVX2; NASM 2.16.03 example that proves the lanes are cleared.","content_html":"<p>XOR-ing a register with itself is the standard way to zero it, and the CPU recognises the pattern as a zeroing idiom, so the result does not wait for the register's old value. The 256-bit form has a catch: <code>vpxor ymm0, ymm0, ymm0</code> is an integer instruction and exists only with AVX2. On an AVX-only CPU, such as Sandy Bridge, the same job is <code>vxorps ymm0, ymm0, ymm0</code>. This NASM 2.16.03 program loads eight 7s, clears the register and checks the last lane.</p>\n<pre data-filename=\"zero.asm\"><code class=\"language-nasm\">default rel\nglobal _start\n\nsection .data align=32\nsevens dd 7, 7, 7, 7, 7, 7, 7, 7\n\nsection .bss align=32\nout resd 8\n\nsection .text\n_start:\n    vmovdqu ymm0, [sevens]\n    vpxor   ymm0, ymm0, ymm0\n    vmovdqu [out], ymm0\n    mov     edi, [out + 28]     ; lane 7\n    vzeroupper\n    mov     eax, 60\n    syscall</code></pre>\n<pre><code class=\"language-text\">$ ./zero; echo $?\n0</code></pre>\n<p>Without the <code>vpxor</code> the status would be 7. The <code>vzeroupper</code> at the end clears the upper halves of all <code>ymm</code> registers, which avoids a penalty when old non-VEX SSE code runs next on some processors. Check for AVX2 at run time with <code>cpuid</code> before using the instruction; the kernel must also have enabled YMM state, which <code>xgetbv</code> reports.</p>","date_published":"2026-11-24T00:52:16+00:00","tags":["Assembly"]},{"id":"https://systemcoding.dev/snippets/check-printf-style-arguments-with-attribute-format-printf-1-2","url":"https://systemcoding.dev/snippets/check-printf-style-arguments-with-attribute-format-printf-1-2","title":"Check printf-style arguments with __attribute__((format(printf, 1, 2)))","summary":"Make GCC 14 check the arguments of your own printf-style logger with __attribute__((format(printf, 1, 2))), the same way it checks printf.","content_html":"<p>A logging function that takes a format string and variadic arguments hides every mismatch from the compiler: a wrong <code>%d</code> becomes a crash at run time. The <code>format</code> attribute tells GCC to treat your function like <code>printf</code>.</p>\n<pre data-filename=\"log.c\"><code class=\"language-c\">void log_msg(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nvoid f(void)\n{\n    log_msg(\"%d\\n\", \"text\");\n}</code></pre>\n<pre><code class=\"language-sh\">gcc -Wall -fno-diagnostics-show-caret -c log.c</code></pre>\n<pre><code class=\"language-text\">log.c: In function 'f':\nlog.c:5:15: warning: format '%d' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]</code></pre>\n<p>The two numbers are positions: the first is the argument that holds the format string, the second is the first variadic argument, so <code>format(printf, 1, 2)</code> fits <code>log_msg(fmt, ...)</code>. For a method in C++ the implicit <code>this</code> counts as argument 1, which shifts both numbers, a common source of a silent wrong check. Use <code>gnu_printf</code> when you need GNU conversions such as <code>%m</code> regardless of the platform's C library. If the function takes a <code>va_list</code> instead of variadic arguments, give 0 as the second number. Without the attribute the code compiles without a word, even under <code>-Wall</code>. See <a href=\"https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Common-Function-Attributes.html\">Common Function Attributes</a>.</p>","date_published":"2026-11-24T00:51:56+00:00","tags":["Toolchains"]},{"id":"https://systemcoding.dev/snippets/define-a-two-argument-syscall-with-syscall-define2","url":"https://systemcoding.dev/snippets/define-a-two-argument-syscall-with-syscall-define2","title":"Define a two-argument syscall with SYSCALL_DEFINE2","summary":"SYSCALL_DEFINE2() declares a system call with two arguments, builds its wrapper, and needs one line in the syscall table (Linux 6.12, x86-64).","content_html":"<p>A new system call is a C function, a table entry and a number. <code>SYSCALL_DEFINE2()</code> is the macro for a call with two arguments: it names the call, takes each argument as a type and a name, and generates the entry point the architecture needs, including the argument handling. This is for Linux 6.12 on x86-64.</p>\n<pre><code class=\"language-c\">/* kernel/demo.c */\n#include &lt;linux/syscalls.h&gt;\n\nSYSCALL_DEFINE2(demo_add, int, a, int, b)\n{\n\treturn a + b;\n}</code></pre>\n<pre><code class=\"language-text\">463\tcommon\tdemo_add\tsys_demo_add</code></pre>\n<p>The text line goes into <code>arch/x86/entry/syscalls/syscall_64.tbl</code>, using the next free number. On a 6.12 tree the last common call is <code>mseal</code> at 462, so the new entry is 463. The name in the table is <code>sys_demo_add</code>, which the macro creates from the first argument. Write the types and names in pairs separated by commas, and do not put a comma between a type and its name.</p>\n<p>The macro does more than a plain function would: on x86-64 it generates a <code>__x64_sys_demo_add</code> wrapper that reads the arguments from the saved registers, and it makes the arguments sign-extend correctly. It also adds the call to the syscall metadata used by tracing. You must also add the prototype to <code>include/linux/syscalls.h</code> when the call is used elsewhere. See <a href=\"https://docs.kernel.org/process/adding-syscalls.html\">adding a new system call</a>.</p>","date_published":"2026-11-24T00:51:36+00:00","tags":["Kernels"]},{"id":"https://systemcoding.dev/snippets/establish-a-base-register-with-balr-12-0-and-using-12","url":"https://systemcoding.dev/snippets/establish-a-base-register-with-balr-12-0-and-using-12","title":"Establish a base register with BALR 12,0 and USING *,12","summary":"Make a program addressable with BALR 12,0 and USING *,12 so the assembler can turn labels into base and displacement on z/OS 3.1.","content_html":"<p>An assembler program has no address of its own until you give it one. <code>BALR 12,0</code> loads register 12 with the address of the next instruction, and <code>USING *,12</code> tells High Level Assembler that this location is in register 12, on z/OS 3.1.</p>\n<pre data-filename=\"base.asm\"><code class=\"language-hlasm\">MYPROG   CSECT\n         BALR  12,0\n         USING *,12\n         LA    2,MSG\n         BR    14\nMSG      DC    C'HELLO'\n         END   MYPROG</code></pre>\n<pre><code class=\"language-text\">LOC    OBJECT CODE    ADDR1 ADDR2  STMT\n000000 05C0                         BALR  12,0\n000002                              USING *,12\n000002 4120 C006                    LA    2,MSG</code></pre>\n<p>The listing is an example of how the assembler resolves <code>MSG</code>, and the column spacing in a real listing differs a little. <code>BALR 12,0</code> is at offset 0 and is 2 bytes long, so register 12 holds the address of offset 2. <code>MSG</code> is at offset 8, after the 2-byte <code>BALR</code>, the 4-byte <code>LA</code> and the 2-byte <code>BR</code>, which from base 2 is displacement 6, so the <code>LA</code> is built as base 12, displacement <code>006</code>, which is the <code>C006</code> in the object code.</p>\n<p>The second operand of 0 means \"do not branch\", so <code>BALR</code> only saves the address. <code>BASR</code> does the same without setting the high-order status bits in the register, and it is the form for new code. A base register addresses 4,096 bytes from where you point it, so a larger program needs more bases or relative-branch instructions.</p>","date_published":"2026-11-24T00:51:16+00:00","tags":["Mainframe"]},{"id":"https://systemcoding.dev/snippets/accept-exactly-four-can-ids-with-filter-list-mode","url":"https://systemcoding.dev/snippets/accept-exactly-four-can-ids-with-filter-list-mode","title":"Accept exactly four CAN IDs with filter list mode","summary":"Accept exactly four CAN standard IDs on STM32 bxCAN with one filter bank in 16-bit identifier list mode, shifting each ID left by five.","content_html":"<p>One bxCAN filter bank in 16-bit list mode holds four 11-bit identifiers, and a frame passes only when its ID equals one of them. That is the cheapest way to listen to a handful of messages without receiving anything else. With the STM32F4 HAL, the four slots reuse the mask fields of the filter structure.</p>\n<pre><code class=\"language-c\">CAN_FilterTypeDef f = {0};\nf.FilterBank           = 0;\nf.FilterMode           = CAN_FILTERMODE_IDLIST;\nf.FilterScale          = CAN_FILTERSCALE_16BIT;\nf.FilterIdHigh         = 0x101 &lt;&lt; 5;     // slot 1\nf.FilterIdLow          = 0x102 &lt;&lt; 5;     // slot 2\nf.FilterMaskIdHigh     = 0x103 &lt;&lt; 5;     // slot 3 (holds an ID, not a mask)\nf.FilterMaskIdLow      = 0x104 &lt;&lt; 5;     // slot 4\nf.FilterFIFOAssignment = CAN_RX_FIFO0;\nf.FilterActivation     = ENABLE;\nf.SlaveStartFilterBank = 14;\n\nif (HAL_CAN_ConfigFilter(&amp;hcan1, &amp;f) != HAL_OK) Error_Handler();</code></pre>\n<p>Each 16-bit register holds <code>STID[10:0]</code> in bits 15 to 5, then <code>RTR</code>, <code>IDE</code> and three extended-ID bits below. Shifting by five puts the standard ID in place and leaves <code>RTR</code> and <code>IDE</code> at zero, so only standard data frames match. A remote frame for <code>0x101</code> is rejected unless you set the <code>RTR</code> bit in that slot.</p>\n<p>The names are misleading in list mode. <code>FilterMaskIdHigh</code> and <code>FilterMaskIdLow</code> are not masks there but IDs three and four. If you need more than four IDs, use a second bank.</p>","date_published":"2026-11-24T00:50:56+00:00","tags":["Embedded"]},{"id":"https://systemcoding.dev/snippets/limit-cpu-seconds-with-rlimit-cpu-and-catch-sigxcpu","url":"https://systemcoding.dev/snippets/limit-cpu-seconds-with-rlimit-cpu-and-catch-sigxcpu","title":"Limit CPU seconds with RLIMIT_CPU and catch SIGXCPU","summary":"Cap the CPU time a process may use with setrlimit and RLIMIT_CPU on Linux 6.12, catch the SIGXCPU warning at the soft limit, and know when SIGKILL follows.","content_html":"<p>A runaway loop in a plugin or a batch job should not burn a core forever. <code>RLIMIT_CPU</code> limits the CPU seconds a process may consume, and it has two stages. When the process reaches the soft limit, the kernel sends <code>SIGXCPU</code>, which you can catch to clean up. If it keeps running, it gets <code>SIGXCPU</code> again every second, until the hard limit, where <code>SIGKILL</code> ends it. See [<code>setrlimit(2)</code>](https://man7.org/linux/man-pages/man2/setrlimit.2.html).</p>\n<pre data-filename=\"cpulimit.c\"><code class=\"language-c\">#include &lt;signal.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;sys/resource.h&gt;\n#include &lt;unistd.h&gt;\n\nstatic void on_xcpu(int sig) {\n    (void)sig;\n    write(1, \"SIGXCPU: out of CPU budget\\n\", 27);\n}\n\nint main(void) {\n    signal(SIGXCPU, on_xcpu);\n\n    struct rlimit lim = { .rlim_cur = 1, .rlim_max = 3 };\n    setrlimit(RLIMIT_CPU, &amp;lim);\n\n    for (;;) { }\n}</code></pre>\n<pre><code class=\"language-text\">SIGXCPU: out of CPU budget\nSIGXCPU: out of CPU budget\nKilled</code></pre>\n<p>The soft limit of one CPU second fires the handler at 1 s and again at 2 s; at 3 s the hard limit is reached and the shell reports <code>Killed</code>. The count of handler lines can differ by one depending on where the tick falls.</p>\n<p>The limit counts CPU time, not wall time: a process that sleeps or waits on I/O does not use it up, so it is no protection against a hang. It also covers all threads together. The handler only calls <code>write</code>, which is on the list of functions safe in a signal handler. A soft limit above the hard limit is rejected with <code>EINVAL</code>, and an unprivileged process can lower the hard limit but never raise it again.</p>","date_published":"2026-11-24T00:50:36+00:00","tags":["Systems Programming"]},{"id":"https://systemcoding.dev/snippets/request-an-adapter-with-instance-request-adapter-in-wgpu","url":"https://systemcoding.dev/snippets/request-an-adapter-with-instance-request-adapter-in-wgpu","title":"Request an adapter with Instance::request_adapter in wgpu","summary":"Ask wgpu 24 for a high-performance GPU adapter with Instance::request_adapter, handle the Option it returns and print the adapter's name and backend.","content_html":"<p>This is the first call in any wgpu program: pick the physical GPU you will use. An adapter represents one GPU on one backend, and requesting one is asynchronous, so a native program drives it with <code>pollster::block_on</code>. The code below is for wgpu 24.</p>\n<pre><code class=\"language-rust\">use wgpu::{Instance, PowerPreference, RequestAdapterOptions};\n\nfn main() {\n    let instance = Instance::default();\n    let adapter = pollster::block_on(instance.request_adapter(&amp;RequestAdapterOptions {\n        power_preference: PowerPreference::HighPerformance,\n        force_fallback_adapter: false,\n        compatible_surface: None,\n    }))\n    .expect(\"no suitable GPU adapter\");\n\n    let info = adapter.get_info();\n    println!(\"adapter: {} ({:?})\", info.name, info.backend);\n}</code></pre>\n<pre><code class=\"language-text\">adapter: Apple M2 (Metal)</code></pre>\n<p>That output is from a MacBook with an M2; on Linux it names the Vulkan device and on Windows it is usually DX12. The result is an <code>Option</code> in wgpu 24, so <code>None</code> means no adapter matched, and later releases changed it to a <code>Result</code> that carries the reason.</p>\n<p><code>compatible_surface</code> should be set to your window's surface whenever you will draw to one, because on a laptop the adapter that can present to the window may not be the one that was fastest in the abstract. <code>HighPerformance</code> prefers a discrete GPU, <code>LowPower</code> the integrated one, and setting <code>force_fallback_adapter</code> selects a software renderer where one exists, which is useful in CI.</p>\n<p>Use <code>instance.enumerate_adapters(Backends::all())</code> on native targets to list all adapters when you want to let the user choose. That function does not exist in the browser build.</p>","date_published":"2026-11-24T00:50:16+00:00","tags":["GPU"]},{"id":"https://systemcoding.dev/snippets/get-your-process-id-with-the-getpid-syscall-39","url":"https://systemcoding.dev/snippets/get-your-process-id-with-the-getpid-syscall-39","title":"Get your process ID with the getpid syscall (39)","summary":"Call getpid (39) in GNU as 2.43 and print the result as decimal digits, built backwards with div by 10; the pid differs every run.","content_html":"<p><code>getpid</code> is system call 39 and takes no arguments; the process ID comes back in <code>rax</code>. Turning it into text is the real work, since there is no <code>printf</code> here. The usual method divides by 10 repeatedly, storing each remainder as a digit from the end of a buffer backwards so the digits come out in order. This GNU as 2.43 program prints the PID and a newline.</p>\n<pre data-filename=\"getpid.s\"><code class=\"language-asm\">    .bss\nbuf:    .skip   20\n    .data\nnl:     .byte   10\n\n    .text\n    .globl  _start\n_start:\n    mov     $39, %eax\n    syscall                     /* rax = pid */\n    lea     buf+20(%rip), %rdi  /* one past the end */\n    mov     $10, %ecx\n1:  xor     %edx, %edx\n    div     %rcx                /* rax /= 10, rdx = digit */\n    add     $48, %dl            /* '0' */\n    dec     %rdi\n    mov     %dl, (%rdi)\n    test    %rax, %rax\n    jnz     1b\n    lea     buf+20(%rip), %rdx\n    sub     %rdi, %rdx          /* digit count */\n    mov     %rdi, %rsi\n    mov     $1, %edi\n    mov     $1, %eax\n    syscall\n    mov     $1, %edx\n    lea     nl(%rip), %rsi\n    mov     $1, %eax\n    syscall\n    xor     %edi, %edi\n    mov     $60, %eax\n    syscall</code></pre>\n<pre><code class=\"language-text\">$ ./getpid\n48213</code></pre>\n<p>The number printed will differ on every run, and in a container it may be small. <code>div %rcx</code> divides <code>rdx:rax</code>, so <code>rdx</code> must be zeroed first, which is the <code>xor</code> at the top of the loop. A pid of 0 would print <code>0</code>, since the loop body runs once before testing. <code>getpid</code> cannot fail, so there is no error path. On Linux 6.12 every call enters the kernel, because <code>getpid</code> has no vDSO shortcut.</p>","date_published":"2026-11-24T00:49:56+00:00","tags":["Assembly"]},{"id":"https://systemcoding.dev/snippets/report-loops-that-failed-to-vectorise-with-fopt-info-vec-missed","url":"https://systemcoding.dev/snippets/report-loops-that-failed-to-vectorise-with-fopt-info-vec-missed","title":"Report loops that failed to vectorise with -fopt-info-vec-missed","summary":"Find out which loops GCC 14 refused to vectorise with -fopt-info-vec-missed, which prints the loop's location and the reason it gave up.","content_html":"<p>When a hot loop is slower than you expected, the first question is whether the vectoriser touched it. <code>-fopt-info-vec-missed</code> prints a note for every loop it looked at and rejected, with the line of the loop.</p>\n<pre data-filename=\"s.c\"><code class=\"language-c\">float total(const float *a, int n)\n{\n    float sum = 0.0f;\n    for (int i = 0; i &lt; n; i++)\n        sum += a[i];\n    return sum;\n}</code></pre>\n<pre><code class=\"language-sh\">gcc -O3 -fopt-info-vec-missed -c s.c 2&gt;&amp;1 | grep \"couldn't vectorize\"</code></pre>\n<pre><code class=\"language-text\">s.c:4:5: missed: couldn't vectorize loop</code></pre>\n<p>That line is followed by others that give the reason, and for this loop the reason is that adding floats in a different order changes the result, which <code>-O3</code> alone is not allowed to do. Adding <code>-fassociative-math</code> together with <code>-fno-signed-zeros</code> and <code>-fno-trapping-math</code>, or <code>-ffast-math</code>, lifts the restriction, at the price of different rounding. The reason lines contain internal names that change between GCC releases, so read them as hints. The variant <code>-fopt-info-vec-optimized</code> reports the loops that did vectorise, and <code>-fopt-info-vec-all</code> both. The flags are documented under <a href=\"https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Developer-Options.html\">Developer Options</a> for GCC 14.2.</p>","date_published":"2026-11-24T00:49:36+00:00","tags":["Toolchains"]},{"id":"https://systemcoding.dev/snippets/allocate-an-ethernet-net-device-with-alloc-etherdev","url":"https://systemcoding.dev/snippets/allocate-an-ethernet-net-device-with-alloc-etherdev","title":"Allocate an Ethernet net_device with alloc_etherdev","summary":"alloc_etherdev() allocates a net_device with Ethernet defaults and your private struct behind it; fetch that struct with netdev_priv() (Linux 6.12).","content_html":"<p>A network driver starts by allocating a <code>struct net_device</code>. <code>alloc_etherdev()</code> does that and fills in the Ethernet defaults, such as the 1500 byte MTU and <code>ether_setup()</code> values, and it appends room for your private data in the same allocation. The sample is for Linux 6.12.</p>\n<pre><code class=\"language-c\">struct demo_priv {\n\tvoid __iomem *base;\n\tstruct napi_struct napi;\n};\n\nstatic int demo_probe(struct platform_device *pdev)\n{\n\tstruct net_device *ndev;\n\tstruct demo_priv *priv;\n\n\tndev = alloc_etherdev(sizeof(*priv));\n\tif (!ndev)\n\t\treturn -ENOMEM;\n\n\tSET_NETDEV_DEV(ndev, &amp;pdev-&gt;dev);\n\tpriv = netdev_priv(ndev);\n\tplatform_set_drvdata(pdev, ndev);\n\treturn 0;\n}</code></pre>\n<p><code>netdev_priv()</code> returns the memory right behind the <code>net_device</code>, so there is no second allocation and no pointer to keep. The memory is zeroed and freed with the device by <code>free_netdev()</code>.</p>\n<p><code>SET_NETDEV_DEV()</code> links the network interface to the parent device, which gives sysfs the right path and lets the core use the parent for DMA and power management. On an error path after this point you must call <code>free_netdev()</code>, since the managed <code>devm_alloc_etherdev()</code> is the alternative that frees it for you on unbind. The allocation does not make the interface visible: for that you need <code>register_netdev()</code>. See <a href=\"https://docs.kernel.org/networking/netdevices.html\">the network device API</a>.</p>","date_published":"2026-11-24T00:49:16+00:00","tags":["Kernels"]},{"id":"https://systemcoding.dev/snippets/start-an-exec-with-a-rexx-comment","url":"https://systemcoding.dev/snippets/start-an-exec-with-a-rexx-comment","title":"Start an exec with a /* REXX */ comment","summary":"Start a REXX exec with a first-line comment that contains the word REXX so TSO runs it as REXX on z/OS 3.1.","content_html":"<p>A REXX exec must begin with a comment on line 1, and on z/OS 3.1 the comment must contain the word <code>REXX</code>. That is how TSO tells the exec apart from a CLIST when you run it from a library such as <code>SYSPROC</code>.</p>\n<pre data-filename=\"HELLO\"><code class=\"language-rexx\">/* REXX */\nSAY 'Hello from REXX'</code></pre>\n<pre><code class=\"language-text\">Hello from REXX</code></pre>\n<p>The comment has to start in column 1 of the first line. Without it, an exec found through <code>SYSPROC</code> is treated as a CLIST, and you get CLIST errors on perfectly good REXX statements. Execs found through <code>SYSEXEC</code> are always REXX, but the comment is still required by the language and costs nothing.</p>\n<p>Put a real description after the word, as in <code>/* REXX - list datasets for a user */</code>. The check looks for the word <code>REXX</code> in the first comment, so keep the word there.</p>","date_published":"2026-11-24T00:48:56+00:00","tags":["Mainframe"]},{"id":"https://systemcoding.dev/snippets/set-the-arduino-i2c-clock-to-400-khz-with-wire-setclock","url":"https://systemcoding.dev/snippets/set-the-arduino-i2c-clock-to-400-khz-with-wire-setclock","title":"Set the Arduino I2C clock to 400 kHz with Wire.setClock","summary":"Raise the Arduino I2C bus to 400 kHz by calling Wire.setClock(400000) after Wire.begin, and see what TWBR holds on a 16 MHz ATmega328P.","content_html":"<p>The default Wire clock is 100 kHz. Most sensors and OLED controllers accept 400 kHz Fast-mode, which cuts the time of a full-screen update by about a factor of four. Call <code>Wire.setClock()</code> after <code>Wire.begin()</code>, because <code>begin()</code> resets the speed.</p>\n<pre><code class=\"language-cpp\">#include &lt;Wire.h&gt;\n\nvoid setup() {\n  Serial.begin(115200);\n  Wire.begin();\n  Serial.print(\"TWBR at 100 kHz: \");\n  Serial.println(TWBR);\n  Wire.setClock(400000);\n  Serial.print(\"TWBR at 400 kHz: \");\n  Serial.println(TWBR);\n}\n\nvoid loop() {}</code></pre>\n<p>On an Uno with the AVR core 1.8.x, the bit rate register follows <code>TWBR = (F_CPU / freq - 16) / 2</code> with the prescaler at 1, so 16 MHz gives these values:</p>\n<pre><code class=\"language-text\">TWBR at 100 kHz: 72\nTWBR at 400 kHz: 12</code></pre>\n<p>Every device on the bus must support Fast-mode, or the slowest one sets the limit. Fast-mode also asks for a faster rise time, 300 ns against 1000 ns in the <a href=\"https://www.nxp.com/docs/en/user-guide/UM10204.pdf\">I2C-bus specification</a>, so pull-ups that were fine at 100 kHz may now be too weak. If readings turn to garbage after the change, check the pull-ups before blaming the code.</p>","date_published":"2026-11-24T00:48:36+00:00","tags":["Embedded"]},{"id":"https://systemcoding.dev/snippets/get-the-current-user-name-with-getpwuid-and-geteuid","url":"https://systemcoding.dev/snippets/get-the-current-user-name-with-getpwuid-and-geteuid","title":"Get the current user name with getpwuid and geteuid","summary":"Look up the account name of the effective user in C with geteuid and getpwuid_r on Linux with glibc 2.41, without trusting the USER variable or getlogin.","content_html":"<p><code>getenv(\"USER\")</code> is whatever the parent put there, and <code>getlogin()</code> reads the terminal's login record, which is empty in a daemon, a container or a cron job. The reliable source is the account database, keyed by the effective user id: <code>geteuid</code> for the id and [<code>getpwuid_r</code>](https://man7.org/linux/man-pages/man3/getpwnam.3.html) for the record.</p>\n<pre data-filename=\"whoami.c\"><code class=\"language-c\">#include &lt;pwd.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n\nint main(void) {\n    struct passwd pw, *result;\n    char buf[1024];\n\n    int err = getpwuid_r(geteuid(), &amp;pw, buf, sizeof buf, &amp;result);\n    if (err != 0 || result == NULL) {\n        fprintf(stderr, \"no passwd entry for uid %u\\n\", (unsigned)geteuid());\n        return 1;\n    }\n    printf(\"%s (uid %u)\\n\", pw.pw_name, (unsigned)pw.pw_uid);\n    return 0;\n}</code></pre>\n<pre><code class=\"language-text\">alice (uid 1000)</code></pre>\n<p>The <code>_r</code> variant writes into your buffer, so it is safe from several threads, unlike plain <code>getpwuid</code>, which returns a pointer to static storage that the next lookup overwrites. If the buffer is too small, the call returns <code>ERANGE</code> and you retry with a bigger one; <code>sysconf(_SC_GETPW_R_SIZE_MAX)</code> gives a starting size.</p>\n<p>Two outcomes need handling. A uid with no entry, common in containers started with <code>--user 1234</code>, gives <code>result == NULL</code> and <code>err == 0</code>, so check both. And <code>geteuid</code> is the right id for \"who am I acting as\", while <code>getuid</code> is the one that started the process: they differ in a setuid program, and the name of the effective user is <code>root</code> there.</p>","date_published":"2026-11-24T00:48:16+00:00","tags":["Systems Programming"]},{"id":"https://systemcoding.dev/snippets/configure-a-pin-from-devicetree-with-gpio-pin-configure-dt","url":"https://systemcoding.dev/snippets/configure-a-pin-from-devicetree-with-gpio-pin-configure-dt","title":"Configure a pin from devicetree with gpio_pin_configure_dt","summary":"gpio_pin_configure_dt sets a pin's direction and initial level from a gpio_dt_spec, merging the devicetree active-low flag, on Zephyr 4.2.","content_html":"<p><code>gpio_pin_configure()</code> takes a device, a pin number and flags, three things the devicetree already knows. The <code>_dt</code> variant takes the <code>struct gpio_dt_spec</code> instead, and it also ORs in the flags written next to the pin in the devicetree, so an active-low LED is configured as active-low without any code.</p>\n<pre data-filename=\"src/main.c\"><code class=\"language-c\">#include &lt;zephyr/kernel.h&gt;\n#include &lt;zephyr/drivers/gpio.h&gt;\n#include &lt;zephyr/sys/printk.h&gt;\n\nstatic const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(DT_ALIAS(led0), gpios);\n\nint main(void)\n{\n\tif (!gpio_is_ready_dt(&amp;led)) {\n\t\treturn -ENODEV;\n\t}\n\tint rc = gpio_pin_configure_dt(&amp;led, GPIO_OUTPUT_ACTIVE);\n\n\tprintk(\"configure rc %d\\n\", rc);\n\treturn 0;\n}</code></pre>\n<pre><code class=\"language-text\">configure rc 0</code></pre>\n<p><code>GPIO_OUTPUT_ACTIVE</code> means \"output, driven to the active level\", so the LED lights at once whether the board wires it high or low. <code>GPIO_OUTPUT_INACTIVE</code> starts it off. Reading <code>led.dt_flags</code> shows the flags that were merged, which is where <code>GPIO_ACTIVE_LOW</code> comes from. The call returns 0 or a negative error, for example when the controller does not support the requested flags. Always run <code>gpio_is_ready_dt()</code> first. See the <a href=\"https://docs.zephyrproject.org/latest/hardware/peripherals/gpio.html\">GPIO API</a>, version 4.2.</p>","date_published":"2026-11-24T00:47:56+00:00","tags":["RTOS"]},{"id":"https://systemcoding.dev/snippets/declare-a-workgroup-size-with-layout-local-size-x-64-in","url":"https://systemcoding.dev/snippets/declare-a-workgroup-size-with-layout-local-size-x-64-in","title":"Declare a workgroup size with layout(local_size_x = 64) in","summary":"Set the local workgroup size of a GLSL compute shader with layout(local_size_x = 64) in, and compute the global index from gl_GlobalInvocationID.","content_html":"<p>This is how a GLSL compute shader says how many invocations make up one workgroup. The declaration is required in a compute shader, and it is fixed at compile time, unlike an OpenCL local size passed at launch.</p>\n<pre><code class=\"language-glsl\">#version 430\nlayout(local_size_x = 64) in;\n\nlayout(std430, binding = 0) buffer Data { uint v[]; };\n\nvoid main()\n{\n    uint i = gl_GlobalInvocationID.x;\n    if (i &lt; v.length())\n        v[i] = i * 2u;\n}</code></pre>\n<p>Unspecified dimensions default to 1, so this is a group of 64 by 1 by 1. For a 2D image you would write <code>layout(local_size_x = 16, local_size_y = 16) in;</code>. <code>gl_GlobalInvocationID</code> is <code>gl_WorkGroupID * gl_WorkGroupSize + gl_LocalInvocationID</code>, so the first group covers indices 0 to 63, the second 64 to 127.</p>\n<p>The size is bounded by <code>GL_MAX_COMPUTE_WORK_GROUP_SIZE</code> per dimension and by <code>GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS</code> for the product. OpenGL 4.3 guarantees the invocation limit is at least 1024, and the per-axis limits are at least 1024 for X and Y and 64 for Z, but real devices differ, so query them:</p>\n<pre><code class=\"language-c\">GLint inv; glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &amp;inv);</code></pre>\n<p>A multiple of 32 or 64 matches the usual hardware group of lanes, but the best number comes from measuring. Use <code>gl_WorkGroupSize</code> inside the shader rather than repeating 64, so the constant lives in one place. Compute shaders need OpenGL 4.3 or <code>GL_ARB_compute_shader</code>; macOS stops at 4.1 and has none.</p>","date_published":"2026-11-24T00:47:36+00:00","tags":["GPU"]},{"id":"https://systemcoding.dev/snippets/exit-every-thread-at-once-with-exit-group-231","url":"https://systemcoding.dev/snippets/exit-every-thread-at-once-with-exit-group-231","title":"Exit every thread at once with exit_group (231)","summary":"Call exit_group (231) instead of exit (60) so every thread ends at once; a GNU as 2.43 program on Linux 6.12 with the status check.","content_html":"<p>Linux has two exit system calls and they differ in scope. <code>exit</code> (60) ends only the calling thread, and the process lives on until its last thread is gone. <code>exit_group</code> (231) ends every thread in the process immediately and sets the process's exit status. The C library's <code>_exit</code> and <code>exit</code> use <code>exit_group</code>, and so should any assembly program that may have created threads. This GNU as 2.43 program exits with status 3 for the whole process.</p>\n<pre data-filename=\"exitgroup.s\"><code class=\"language-asm\">    .text\n    .globl  _start\n_start:\n    mov     $231, %eax          /* exit_group */\n    mov     $3, %edi            /* status */\n    syscall</code></pre>\n<pre><code class=\"language-text\">$ as exitgroup.s -o eg.o &amp;&amp; ld eg.o -o eg &amp;&amp; ./eg; echo $?\n3</code></pre>\n<p>For a single-threaded program the two behave the same, which is why the older number is the one most tutorials show. The difference appears when a thread calls <code>exit</code>: the process keeps running with one thread fewer, and the exit status is only reported after the last one leaves. The <code>exit_group(2)</code> manual page documents the call. Only the low 8 bits of the status reach the parent, so 256 would arrive as 0.</p>","date_published":"2026-11-24T00:47:16+00:00","tags":["Assembly"]},{"id":"https://systemcoding.dev/snippets/turn-one-warning-into-an-error-with-werror-return-type","url":"https://systemcoding.dev/snippets/turn-one-warning-into-an-error-with-werror-return-type","title":"Turn one warning into an error with -Werror=return-type","summary":"Make a missing return fatal without turning every warning into an error, using -Werror=return-type on GCC 14, where it matters most.","content_html":"<p>A function that falls off its end without returning is the one warning worth failing the build for, since the caller reads garbage. <code>-Werror=return-type</code> promotes just that diagnostic and leaves the rest of your warnings as they are.</p>\n<pre data-filename=\"sign.c\"><code class=\"language-c\">int sign(int x)\n{\n    if (x &gt; 0) return 1;\n    if (x &lt; 0) return -1;\n}</code></pre>\n<pre><code class=\"language-sh\">gcc -Wall -Werror=return-type -fno-diagnostics-show-caret -c sign.c</code></pre>\n<pre><code class=\"language-text\">sign.c: In function 'sign':\nsign.c:5:1: error: control reaches end of non-void function [-Werror=return-type]</code></pre>\n<p>The diagnostic points at the closing brace, which is the place the control actually runs out. The <code>-fno-diagnostics-show-caret</code> flag only trims the source excerpt to keep the output short. In C the result is undefined only if the caller uses the value, but in C++ simply flowing off the end is undefined behaviour, and GCC 8 and later may delete the whole path at <code>-O2</code>, so a missing <code>return</code> there can erase code, not only return junk. That is a good reason to make it an error in C++ projects. The <code>-Werror=name</code> form is documented under <a href=\"https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Warning-Options.html\">Warning Options</a>.</p>","date_published":"2026-11-24T00:46:56+00:00","tags":["Toolchains"]},{"id":"https://systemcoding.dev/snippets/get-a-gpio-descriptor-with-devm-gpiod-get","url":"https://systemcoding.dev/snippets/get-a-gpio-descriptor-with-devm-gpiod-get","title":"Get a GPIO descriptor with devm_gpiod_get","summary":"devm_gpiod_get() looks up a named GPIO from the device tree, sets its direction and initial level, and releases it on unbind; use it instead of gpio numbers.","content_html":"<p>The old integer GPIO API is gone from new drivers. The descriptor API finds a line by a connection name taken from the firmware description, so a driver does not hard-code pin numbers. This example is for Linux 6.12.</p>\n<pre><code class=\"language-c\">struct gpio_desc *reset;\n\nreset = devm_gpiod_get(&amp;pdev-&gt;dev, \"reset\", GPIOD_OUT_HIGH);\nif (IS_ERR(reset))\n\treturn dev_err_probe(&amp;pdev-&gt;dev, PTR_ERR(reset),\n\t\t\t     \"cannot get the reset line\\n\");\n\nusleep_range(1000, 2000);\ngpiod_set_value(reset, 0);\t/* release the reset */</code></pre>\n<pre><code class=\"language-text\">demo 10000000.demo: cannot get the reset line</code></pre>\n<p>The text is what you get if the device tree has no <code>reset-gpios</code> property: the lookup returns <code>-ENOENT</code>, which <code>dev_err_probe()</code> reports. The third argument sets the direction and the initial value in one step, which avoids a glitch on the line between the request and the first write.</p>\n<p>The values are logical, not physical. If the property carries <code>GPIO_ACTIVE_LOW</code>, <code>GPIOD_OUT_HIGH</code> drives the pin low, so assert and release read the same way in code on every board. That is the main reason to use this API over raw numbers. The flags are <code>GPIOD_IN</code>, <code>GPIOD_OUT_LOW</code> and <code>GPIOD_OUT_HIGH</code>. See <a href=\"https://docs.kernel.org/driver-api/gpio/consumer.html\">the GPIO consumer guide</a>.</p>","date_published":"2026-11-24T00:46:36+00:00","tags":["Kernels"]},{"id":"https://systemcoding.dev/snippets/send-a-message-with-exec-cics-send-text-erase","url":"https://systemcoding.dev/snippets/send-a-message-with-exec-cics-send-text-erase","title":"Send a message with EXEC CICS SEND TEXT ERASE","summary":"Send plain text to a terminal with EXEC CICS SEND TEXT ERASE in COBOL, which needs no BMS map, on CICS Transaction Server 6.1.","content_html":"<p>The simplest CICS program writes a line to the terminal without a screen map, using <code>SEND TEXT</code>. It is a good first transaction and a quick way to show a status message from a program that does not own a mapset.</p>\n<pre data-filename=\"hello.cbl\"><code class=\"language-cobol\">       WORKING-STORAGE SECTION.\n       01  WS-MSG   PIC X(16) VALUE 'HELLO FROM CICS'.\n       PROCEDURE DIVISION.\n           EXEC CICS SEND TEXT FROM(WS-MSG)\n                LENGTH(LENGTH OF WS-MSG) ERASE\n           END-EXEC.\n           EXEC CICS RETURN END-EXEC.</code></pre>\n<pre><code class=\"language-text\">HELLO FROM CICS</code></pre>\n<p><code>ERASE</code> clears the screen first, so the text appears at the top left. Without it, the text is added to what is already shown.</p>\n<p>The data is sent as typed, and a message longer than the screen is split over pages with the terminal's paging commands, which is a reason to keep status text short. The <code>RETURN</code> ends the task, and the terminal stays on the screen until the user presses a key. On CICS TS 6.1 this works for 3270 terminals and for sessions through CICS Web or TN3270 gateways.</p>","date_published":"2026-11-24T00:46:16+00:00","tags":["Mainframe"]}]}