Lesson 06intermediateProcesses

Advanced Signals with sigaction

Deep dive into sigaction() — the robust, portable replacement for signal(). Covers the sigaction struct anatomy, sa_mask for blocking signals during handling, SA_RESTART and SA_RESETHAND flags, and SA_SIGINFO for accessing detailed signal metadata.

sigactionsa_maskSA_SIGINFOSA_RESTARTsignal-blocking
1

sigaction Struct Reference

A thorough 124-line reference documenting every field and flag of the sigaction struct with inline explanations.

01-basic-info.c
Reference — not run on its ownAnnotated definition of struct sigaction — read it, nothing to run.
2

Basic sigaction Usage

Setting up a signal handler using sigaction instead of signal — the minimal working example.

02-usage.c
/*
 * 02-usage.c — Basic sigaction usage — registering a handler
 *
 * Key concepts: sigaction(), sigemptyset(), signal registration
 * Compile: gcc -o usage 02-usage.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

// Handler function for SIGINT
void sigint_handler(int signum) {
    printf("\n[Handler] Caught signal %d (SIGINT). Exiting gracefully.\n", signum);
    exit(0);
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Basic sigaction() Usage\n");
    printf("  Register a custom handler for SIGINT\n");
    printf("══════════════════════════════════════\n\n");
    struct sigaction sa;

    // Set up the sigaction struct
    sa.sa_handler = sigint_handler;    // Assign handler function
    sa.sa_flags = 0;                    // No special flags
    sigemptyset(&sa.sa_mask);           // Don't block any signals during handler

    // Set up the handler for SIGINT
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error: sigaction failed");
        exit(EXIT_FAILURE);
    }

    printf("[Main] sigaction() registered handler for SIGINT\n");
    printf("[Main] sa_handler = sigint_handler, sa_flags = 0\n");
    printf("[Main] sa_mask = empty (no signals blocked during handler)\n");
    printf("[Main] Process PID: %d\n\n", getpid());
    printf("Press Ctrl+C to trigger SIGINT...\n\n");

    // Infinite loop to keep the program running
    int tick = 0;
    while (1) {
        printf("[Main] Tick %d — Running... (Ctrl+C to exit)\n", ++tick);
        sleep(2);
    }

    return 0;
}
$ gcc -o sigact_usage 02-usage.c
$ ./sigact_usage
Expected Outputclick Run to execute live
══════════════════════════════════════
  Basic sigaction() Usage
  Register a custom handler for SIGINT
══════════════════════════════════════

[Main] sigaction() registered handler for SIGINT
[Main] sa_handler = sigint_handler, sa_flags = 0
[Main] sa_mask = empty (no signals blocked during handler)
[Main] Process PID: 1371

Press Ctrl+C to trigger SIGINT...

[Main] Tick 1 — Running... (Ctrl+C to exit)
[Main] Tick 2 — Running... (Ctrl+C to exit)
[Main] Tick 3 — Running... (Ctrl+C to exit)
[Main] Tick 4 — Running... (Ctrl+C to exit)
[Main] Tick 5 — Running... (Ctrl+C to exit)
^C
[Handler] Caught signal 2 (SIGINT). Exiting gracefully.

[runs until stopped — the site stops it after 8s]
Runs until stopped — stops automatically after 8s
3

Multi-Signal Handling

Registering different handlers for multiple signals (SIGINT, SIGTERM, SIGUSR1) in a single program.

03-multi-signals.c
$ gcc -o multi_sig 03-multi-signals.c
$ ./multi_sig
Runs until stopped — stops automatically after 12sRun pair also opens a second terminal: kill -TERM multi_sigIgnores Ctrl+C on purpose — the second terminal ends it with SIGTERM
4

Signal Blocking with sa_mask

Using sa_mask to block specific signals while a handler is executing, preventing re-entrant handler chaos.

04-using-sa-mask.c
$ gcc -o sa_mask 04-using-sa-mask.c
$ ./sa_mask
Expected Outputclick Run to execute live
══════════════════════════════════════
  sa_mask — Blocking Signals in Handler
  SIGUSR2 is blocked while SIGUSR1 handler runs
══════════════════════════════════════

[Main] SIGUSR1 handler registered (sa_mask includes SIGUSR2)
[Main] SIGUSR2 handler registered (sa_mask empty)

[Main] Process PID: 1385
[Main] Step 1: kill -SIGUSR1 1385   (starts 5s handler)
[Main] Step 2: kill -SIGUSR2 1385   (within 5s — will be blocked!)
[Main] Watch: SIGUSR2 handler runs AFTER SIGUSR1 handler finishes.

[Main] Tick 1 — Waiting for signals... (PID 1385)
[Main] Tick 2 — Waiting for signals... (PID 1385)
[Main] Tick 3 — Waiting for signals... (PID 1385)
[Main] Tick 4 — Waiting for signals... (PID 1385)
[Main] Tick 5 — Waiting for signals... (PID 1385)
^C

[runs until stopped — the site stops it after 8s]
Runs until stopped — stops automatically after 8s
5

SA_RESTART and SA_RESETHAND

SA_RESTART automatically restarts interrupted syscalls; SA_RESETHAND makes a handler fire only once.

05-some-flags.c
/*
 * 05-some-flags.c — sigaction flags — SA_RESTART, SA_RESETHAND
 *
 * Key concepts: SA_RESTART (auto-retry interrupted syscalls), SA_RESETHAND (one-shot)
 * Compile: gcc -o flags 05-some-flags.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>


// here we show example of two flags
// SA_RESTART and SA_RESETHAND
// SA_RESTART is used to restart the system call if it was interrupted by the signal (sleep in this case)
// SA_RESETHAND is used to reset the handler to default after the first signal

// here we want to use :
// kill -SIGUSR1 <pid>
// than again
// kill -SIGUSR1 <pid>

// Handler for SIGUSR1
void handle_sigusr1(int signum) {
    printf("\n[Handler] Caught SIGUSR1 (signal %d).\n", signum);
    printf("[Handler] SA_RESETHAND: this handler is NOW reset to default (SIG_DFL).\n");
    printf("[Handler] SA_RESTART:   the sleep() that was interrupted will auto-restart.\n");
    printf("[Handler] Next SIGUSR1 will TERMINATE the process (default action).\n\n");
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  sigaction Flags Demo\n");
    printf("  SA_RESTART | SA_RESETHAND\n");
    printf("══════════════════════════════════════\n\n");
    struct sigaction sa;

    // Setup handler for SIGUSR1 with SA_RESTART and SA_RESETHAND flags
    sa.sa_handler = handle_sigusr1;
    sa.sa_flags = SA_RESTART | SA_RESETHAND; // Restart interrupted syscalls and reset handler
    sigemptyset(&sa.sa_mask);                  // No additional signals blocked

    if (sigaction(SIGUSR1, &sa, NULL) == -1) {
        perror("Error: sigaction for SIGUSR1 failed");
        exit(EXIT_FAILURE);
    }

    printf("[Main] sa_flags = SA_RESTART | SA_RESETHAND\n");
    printf("[Main]   SA_RESTART  — interrupted sleep() auto-restarts\n");
    printf("[Main]   SA_RESETHAND — handler reverts to SIG_DFL after first catch\n\n");
    printf("[Main] Process PID: %d\n", getpid());
    printf("[Main] 1st: kill -SIGUSR1 %d  → handler runs, then resets\n", getpid());
    printf("[Main] 2nd: kill -SIGUSR1 %d  → default action (terminate!)\n\n", getpid());

    // Infinite loop to keep the program running and handling signals
    int tick = 0;
    while (1) {
        printf("[Main] Tick %d — Waiting for SIGUSR1... (PID %d)\n", ++tick, getpid());
        sleep(4);
    }

    return 0;
}
$ gcc -o sa_flags 05-some-flags.c
$ ./sa_flags
Runs until stopped — stops automatically after 12sRun pair also opens a second terminal: kill -SIGUSR1 sa_flags (twice)The second SIGUSR1 kills it on purpose (SA_RESETHAND restored the default action)
6

SA_SIGINFO — Detailed Signal Info

Using SA_SIGINFO to receive a siginfo_t struct with the sender PID, signal code, and other metadata.

06-sig-info.c
/*
 * 06-sig-info.c — SA_SIGINFO — getting detailed signal information
 *
 * Key concepts: SA_SIGINFO, siginfo_t, si_pid, si_uid, si_signo
 * Compile: gcc -o siginfo 06-sig-info.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

// Enhanced handler for SIGUSR1 using SA_SIGINFO

// YOU DONT NEED TO USE SA_SIGINFO in the course/assigments
// it can be helpful in some cases, but its not mandatory!!
// (also the sets are not mandatory, but whatever)

//to use this program we need to send the signal with the kill command
// kill -SIGUSR1 <pid>

void handle_sigusr1(int signum, siginfo_t *info, void *context) {
    printf("\n[Handler] ── Signal Received ──────────────────\n");
    printf("[Handler] Signal:       %d (SIGUSR1)\n", signum);
    printf("[Handler] Sender PID:   %d\n", info->si_pid);
    printf("[Handler] Sender UID:   %d\n", info->si_uid);
    printf("[Handler] Signal code:  %d\n", info->si_code);
    printf("[Handler] Value (int):  %d\n", info->si_value.sival_int);
    printf("[Handler] Errno:        %d\n", info->si_errno);
    printf("[Handler] Address:      %p\n", info->si_addr);
    printf("[Handler] User time:    %ld\n", info->si_utime);
    printf("[Handler] System time:  %ld\n", info->si_stime);
    printf("[Handler] ────────────────────────────────────\n\n");
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  SA_SIGINFO — Detailed Signal Info\n");
    printf("  Access siginfo_t fields in handler\n");
    printf("══════════════════════════════════════\n\n");
    struct sigaction sa;

    // Setup handler for SIGUSR1 with SA_SIGINFO flag
    sa.sa_sigaction = handle_sigusr1;
    sa.sa_flags = SA_SIGINFO; // Enable extended signal information
    sigemptyset(&sa.sa_mask); // No additional signals blocked

    if (sigaction(SIGUSR1, &sa, NULL) == -1) {
        perror("Error: sigaction for SIGUSR1 failed");
        exit(EXIT_FAILURE);
    }

    printf("[Main] Using SA_SIGINFO flag — handler gets siginfo_t struct\n");
    printf("[Main] siginfo_t provides: sender PID, UID, signal code, etc.\n\n");
    printf("[Main] Process PID: %d\n", getpid());
    printf("[Main] Run: kill -SIGUSR1 %d\n\n", getpid());

    // Infinite loop to keep the program running
    int tick = 0;
    while (1) {
        printf("[Main] Tick %d — Waiting for SIGUSR1...\n", ++tick);
        sleep(3);
    }

    return 0;
}
$ gcc -o sig_info 06-sig-info.c
$ ./sig_info
Runs until stopped — stops automatically after 10sRun pair also opens a second terminal: kill -SIGUSR1 sig_info
7

Practical Alarm Example

Combining sigaction with alarm() for a practical timed-operation pattern, preparing for exercise 2.

07-before-ex2.c
/*
 * 07-before-ex2.c — Practical alarm example — preparation for exercise 2
 *
 * Key concepts: alarm(), sigaction, practical signal usage
 * Compile: gcc -o ex2 07-before-ex2.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>


int global_flag = 1;

void handle_sigalrm(int signum) {
    printf("\n[Handler] Time's up! Caught SIGALRM (signal %d).\n", signum);
    global_flag = 0;
}

int main() {
    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Timed Input with alarm() + sigaction\n");
    printf("  Enter numbers before the timer runs out!\n");
    printf("══════════════════════════════════════\n\n");
    const int seconds = 5;
    struct sigaction sa;

    sa.sa_handler = handle_sigalrm;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);

    if (sigaction(SIGALRM, &sa, NULL) == -1) {
        perror("Error: sigaction for SIGALRM failed");
        exit(EXIT_FAILURE);
    }

    printf("[Main] SIGALRM handler registered.\n");
    printf("[Main] alarm(%d) gives you %d seconds per round.\n\n", seconds, seconds);

    int best = 0;
    for (int i = 0; i < 10; i++) {
        global_flag = 1;
        int counter = 0;
        printf("── Round %d/10 ──────────────────────\n", i + 1);
        while(global_flag)
        {
            alarm(seconds);
            printf("  Enter a number (%ds timer): ", seconds);
            fflush(stdout);
            int number;
            if (scanf("%d", &number) == 1) {
                printf("  Got: %d (entry #%d)\n", number, counter + 1);
            }
            counter++;
        }
        printf("[Main] Round %d: you entered %d numbers before timeout.\n\n", i + 1, counter);
        if(counter > best)
        {
            best = counter;
        }
    }

    printf("══════════════════════════════════════\n");
    printf("  Best round: %d entries before timeout\n", best);
    printf("══════════════════════════════════════\n");

    return 0;
}
$ gcc -o before_ex2 07-before-ex2.c
$ ./before_ex2
Expected Outputclick Run to execute live
══════════════════════════════════════
  Timed Input with alarm() + sigaction
  Enter numbers before the timer runs out!
══════════════════════════════════════

[Main] SIGALRM handler registered.
[Main] alarm(5) gives you 5 seconds per round.

── Round 1/10 ──────────────────────
  Enter a number (5s timer): 1
2
3
4
5
6
7
8
9
10
  Got: 1 (entry #1)
  Enter a number (5s timer):   Got: 2 (entry #2)
  Enter a number (5s timer):   Got: 3 (entry #3)
  Enter a number (5s timer):   Got: 4 (entry #4)
  Enter a number (5s timer):   Got: 5 (entry #5)
  Enter a number (5s timer):   Got: 6 (entry #6)
  Enter a number (5s timer):   Got: 7 (entry #7)
  Enter a number (5s timer):   Got: 8 (entry #8)
  Enter a number (5s timer):   Got: 9 (entry #9)
  Enter a number (5s timer):   Got: 10 (entry #10)
  Enter a number (5s timer): 
[Handler] Time's up! Caught SIGALRM (signal 14).
^C

[runs until stopped — the site stops it after 30s]
Asks for input — sample input is one click away

Challenges

ChallengeLesson 06

Survive Ctrl+C

The site presses Ctrl+C after 3 seconds. Install a SIGINT handler with sigaction() so the program prints "Caught Ctrl+C" and keeps counting (the site then stops it with Ctrl+\). Click Edit, change the code, then Run — the site checks how it ended.

survive-ctrl-c.c
/*
 * Challenge (Lessons 03 + 06): survive Ctrl+C
 *
 * This program counts forever. When the site presses Ctrl+C (after 3 seconds),
 * SIGINT's default action kills it.
 *
 * Your task: install a SIGINT handler with sigaction() that prints
 * "Caught Ctrl+C — still running" and lets the program keep counting.
 * Done when the program is still alive after Ctrl+C (the site then stops it with Ctrl+\).
 */
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

// TODO: write a handler:  void on_sigint(int sig) { ... }

int main(void)
{
    // TODO: struct sigaction sa; ... sigaction(SIGINT, &sa, NULL);

    for (int tick = 1; ; tick++) {
        printf("tick %d\n", tick);
        fflush(stdout);
        sleep(1);
    }
}
$ gcc -Wall -o survive survive-ctrl-c.c
$ ./survive

Open Full Terminal

Get a Linux terminal with all 7 files from this lesson pre-loaded. Compile, run, and experiment freely.