Lesson 03intermediateProcesses

Introduction to Signals

Signals with signal(): default actions, catching and ignoring SIGINT, kill() between processes and the kill command from another terminal, SIGALRM timers, one-shot handlers, the safe flag pattern for a graceful shutdown, and signal() vs sigaction().

signalkillSIGINTSIGALRMsig_atomic_t
1

Basic Signal Handling

Registering a handler for SIGINT (Ctrl+C) using the signal() function.

01-basic_signals.c
/*
 * 01-basic_signals.c — Catching SIGINT (Ctrl+C) with signal()
 *
 * Demonstrates: Registering a signal handler with signal()
 * Key concepts: SIGINT, signal handlers, the program keeps running after catching
 * Compile: gcc -o signals 01-basic_signals.c
 * Run:     ./signals   (press Ctrl+C to trigger the handler)
 */

#include <sys/types.h>
#include <signal.h>    // for signal(), SIGINT
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    // for sleep()

void catch_int(int sig_num);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Catching SIGINT (Ctrl+C) with signal()\n");
    printf("══════════════════════════════════════\n\n");
    // Register catch_int as the handler for SIGINT (Ctrl+C)
    // signal() returns SIG_ERR on failure
    signal(SIGINT, catch_int);

    printf("\n");
    printf("[Main PID %d] Running... Press Ctrl+C to trigger the signal handler.\n", getpid());
    printf("  (The handler catches SIGINT but doesn't exit — try pressing Ctrl+C multiple times!)\n");
    printf("  (To actually quit, press Ctrl+\\ which sends SIGQUIT)\n\n");

    int count = 0;
    while (1) {
        printf("[Main PID %d] Still running... (tick %d)\n", getpid(), ++count);
        sleep(2);
    }

    return 0;
}

void catch_int(int sig_num) {
   printf("\n[Signal Handler] Caught signal %d (SIGINT) — Ctrl+C pressed! But I'm not exiting.\n", sig_num);
    //exit(0); 
 
}
$ gcc -o basic_sig 01-basic_signals.c
$ ./basic_sig
Expected Outputclick Run to execute live
══════════════════════════════════════
  Catching SIGINT (Ctrl+C) with signal()
══════════════════════════════════════


[Main PID 828] Running... Press Ctrl+C to trigger the signal handler.
  (The handler catches SIGINT but doesn't exit — try pressing Ctrl+C multiple times!)
  (To actually quit, press Ctrl+\ which sends SIGQUIT)

[Main PID 828] Still running... (tick 1)
[Main PID 828] Still running... (tick 2)
^C
[Signal Handler] Caught signal 2 (SIGINT) — Ctrl+C pressed! But I'm not exiting.
[Main PID 828] Still running... (tick 3)
[Main PID 828] Still running... (tick 4)
[Main PID 828] Still running... (tick 5)
^\Quit                       (core dumped) ./basic_sig

[runs until stopped — the site stops it after 7s]
Runs until stopped — stops automatically after 7sThe site presses Ctrl+C after 2.5 s: the handler runs and the program keeps going. Ctrl+\ (SIGQUIT) stops it.
2

No Handler: the Default Action

raise(SIGUSR1) with no handler installed: the default action terminates the program — the exit chip shows "Killed by SIGUSR1 (10)" and the last line is never printed.

01a-default-action.c
/*
 * 01a-default-action.c — No handler installed? Then the signal's DEFAULT action happens
 *
 * Key concepts: default actions, raise(), SIGUSR1, why a process "dies" from a signal
 * Compile: gcc -o default_action 01a-default-action.c
 * Run:     ./default_action      (look at the exit chip: "Killed by SIGUSR1")
 *
 * Every signal has a default action: most terminate the process (SIGINT, SIGTERM, SIGUSR1...),
 * some also dump core (SIGSEGV, SIGQUIT), SIGCHLD is ignored, SIGSTOP stops it.
 * raise(sig) sends a signal to the calling process itself.
 */
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

int main(void)
{
    printf("[PID %d] No handler for SIGUSR1 is installed.\n", getpid());
    printf("[PID %d] Sending SIGUSR1 to myself with raise()...\n", getpid());
    fflush(stdout);                        // the default action ends us without flushing

    raise(SIGUSR1);                        // default action for SIGUSR1: terminate

    printf("This line is never printed.\n");
    return 0;
}
$ gcc -o default_action 01a-default-action.c
$ ./default_action
Expected Outputclick Run to execute live
[PID 866] No handler for SIGUSR1 is installed.
[PID 866] Sending SIGUSR1 to myself with raise()...
User defined signal 1      ./default_action
Killed by SIGUSR1 on purpose: that is the default action
3

Ignoring Signals

Using SIG_IGN to make a process immune to specific signals like SIGINT.

02-ignore_signal.c
/*
 * 02-ignore_signal.c — Ignoring signals with SIG_IGN
 *
 * Demonstrates: Using SIG_IGN to make a process immune to SIGINT
 * Key concepts: SIG_IGN, Ctrl+C won't stop this program (use kill -9 or close terminal)
 * Compile: gcc -o ignore 02-ignore_signal.c
 * Run:     ./ignore   (Ctrl+C will NOT work — use Ctrl+\ for SIGQUIT or kill the process)
 */

#include <sys/types.h>
#include <signal.h>    // for signal(), SIG_IGN, SIGINT
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    // for sleep()

void catch_int(int sig_num);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Ignoring signals with SIG_IGN\n");
    printf("══════════════════════════════════════\n\n");
    // SIG_IGN = "ignore this signal" — Ctrl+C will be silently discarded
    signal(SIGINT, SIG_IGN);

    printf("\n");
    printf("[PID %d] SIGINT (Ctrl+C) is now IGNORED.\n", getpid());
    printf("  Try pressing Ctrl+C — nothing will happen!\n");
    printf("  To quit: press Ctrl+\\ (sends SIGQUIT, which is NOT ignored)\n\n");

    int count = 0;
    while (1) {
        printf("[PID %d] Still running... (tick %d)\n", getpid(), ++count);
        sleep(2);
    }

    return 0;
}

void catch_int(int sig_num) {
   printf("Caught signal %d\n", sig_num);
    exit(0); 
 
}
$ gcc -o ignore_sig 02-ignore_signal.c
$ ./ignore_sig
Expected Outputclick Run to execute live
══════════════════════════════════════
  Ignoring signals with SIG_IGN
══════════════════════════════════════


[PID 870] SIGINT (Ctrl+C) is now IGNORED.
  Try pressing Ctrl+C — nothing will happen!
  To quit: press Ctrl+\ (sends SIGQUIT, which is NOT ignored)

[PID 870] Still running... (tick 1)
[PID 870] Still running... (tick 2)
^C[PID 870] Still running... (tick 3)
[PID 870] Still running... (tick 4)
^\Quit                       (core dumped) ./ignore_sig

[runs until stopped — the site stops it after 7s]
Runs until stopped — stops automatically after 7sThe site presses Ctrl+C after 2.5 s and nothing happens — SIGINT is ignored. Ctrl+\ (SIGQUIT) stops it.
4

kill(): the Parent Signals Its Child

The parent lets its child work for 3 seconds, sends SIGTERM with kill(), and waitpid() reports which signal ended it — kill() only sends a signal; the default action does the killing.

02a-kill-child.c
/*
 * 02a-kill-child.c — kill(): one process sends a signal to another
 *
 * Key concepts: kill(pid, sig), SIGTERM, waitpid + WIFSIGNALED/WTERMSIG (Lesson 02)
 * Compile: gcc -o kill_child 02a-kill-child.c
 * Run:     ./kill_child
 *
 * Despite its name, kill() just SENDS a signal. SIGTERM's default action terminates the
 * child, and the parent sees exactly which signal ended it in the waitpid() status.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>    // strsignal
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    pid_t child = fork();
    if (child == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (child == 0) {                                  // child: work forever
        for (int i = 1; ; i++) {
            printf("  [Child %d] working... %d\n", getpid(), i);
            fflush(stdout);
            sleep(1);
        }
    }

    sleep(3);                                          // parent: let it work a little
    printf("[Parent %d] kill(%d, SIGTERM)\n", getpid(), child);
    fflush(stdout);
    if (kill(child, SIGTERM) == -1) {
        perror("kill");
        return EXIT_FAILURE;
    }

    int status;
    waitpid(child, &status, 0);
    if (WIFSIGNALED(status))
        printf("[Parent] child ended by signal %d (%s)\n", WTERMSIG(status), strsignal(WTERMSIG(status)));
    return EXIT_SUCCESS;
}
$ gcc -o kill_child 02a-kill-child.c
$ ./kill_child
Expected Outputclick Run to execute live
  [Child 888] working... 1
  [Child 888] working... 2
  [Child 888] working... 3
[Parent 887] kill(888, SIGTERM)
[Parent] child ended by signal 15 (Terminated)
5

Signals from Another Terminal

The program waits in pause() and reacts to SIGUSR1, SIGUSR2 and SIGTERM. Run pair opens a second terminal that sends them with the kill command, one by one.

02b-signals-from-terminal.c
/*
 * 02b-signals-from-terminal.c — Receive signals sent with the `kill` command from another terminal
 *
 * Key concepts: SIGUSR1/SIGUSR2, the kill command, pause(), one handler for several signals
 * Compile: gcc -o sigusr 02b-signals-from-terminal.c
 * Run:     ./sigusr      then, in a second terminal:  kill -USR1 <pid>   kill -USR2 <pid>   kill -TERM <pid>
 *          (Run pair does it for you in the right-hand terminal)
 *
 * SIGUSR1 and SIGUSR2 mean whatever your program decides. Here SIGTERM ends the loop politely.
 */
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

volatile sig_atomic_t last = 0;            // written in the handler, read in main

void on_signal(int sig)
{
    last = sig;                            // keep handlers tiny: just remember what came
}

int main(void)
{
    signal(SIGUSR1, on_signal);
    signal(SIGUSR2, on_signal);
    signal(SIGTERM, on_signal);

    printf("[PID %d] waiting for signals — try: kill -USR1 %d\n", getpid(), getpid());
    fflush(stdout);

    for (;;) {
        pause();                           // sleep until any signal arrives
        if (last == SIGUSR1)
            printf("  got SIGUSR1 — user signal 1\n");
        else if (last == SIGUSR2)
            printf("  got SIGUSR2 — user signal 2\n");
        else if (last == SIGTERM) {
            printf("  got SIGTERM — cleaning up and exiting\n");
            return 0;
        }
        fflush(stdout);
    }
}
$ gcc -o sigusr 02b-signals-from-terminal.c
$ ./sigusr
Run pair also opens a second terminal: kill -USR1, -USR2, -TERM
6

SIGALRM Countdown Timer

Building a countdown timer using alarm() and SIGALRM — the signal fires after a specified number of seconds.

03-sig_alarm.c
/*
 * 03-sig_alarm.c — Using alarm() for a countdown timer
 *
 * Demonstrates: SIGALRM delivery after a timed delay
 * Key concepts: alarm(seconds) schedules a SIGALRM, only one alarm active at a time
 * Compile: gcc -o alarm 03-sig_alarm.c
 * Run:     ./alarm   (waits 5 seconds, then prints and exits)
 */

#include <stdio.h>
#include <stdlib.h>    // for exit()
#include <unistd.h>    // for alarm()
#include <signal.h>    // for signal(), SIGALRM

void handle_alarm(int sig);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Using alarm() for a countdown timer\n");
    printf("══════════════════════════════════════\n\n");
    int countdown = 5;

    // Register the signal handler
    signal(SIGALRM, handle_alarm);

    // Set the alarm for 5 seconds
    printf("\n");
    printf("[Main PID %d] Setting alarm(%d) — SIGALRM will fire in %d seconds.\n\n", getpid(), countdown, countdown);
    alarm(countdown);

    printf("  Waiting for the alarm...\n");
    fflush(stdout);
    while (1) {
        sleep(1);
    }

    return 0;
}

void handle_alarm(int sig) {
    printf("\n[Signal Handler] SIGALRM received (signal %d) — time's up! Exiting.\n", sig);
    exit(0); // Exit the program
}
$ gcc -o sig_alarm 03-sig_alarm.c
$ ./sig_alarm
Expected Outputclick Run to execute live
══════════════════════════════════════
  Using alarm() for a countdown timer
══════════════════════════════════════


[Main PID 949] Setting alarm(5) — SIGALRM will fire in 5 seconds.

  Waiting for the alarm...

[Signal Handler] SIGALRM received (signal 14) — time's up! Exiting.
7

One-Shot Handler

A handler that resets itself to SIG_DFL after the first catch, so the second signal terminates the process.

04-sig_init_once.c
/*
 * 04-sig_init_once.c — One-shot signal handler (catch once, then default)
 *
 * Demonstrates: Restoring default signal behavior with SIG_DFL inside a handler
 * Key concepts: First Ctrl+C is caught, second Ctrl+C kills the process
 * Compile: gcc -o once 04-sig_init_once.c
 * Run:     ./once   (press Ctrl+C twice)
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    // for getpid(), sleep()
#include <signal.h>    // for signal(), SIGINT, SIG_DFL

void custom_handler(int sig) {
    printf("\n[Handler] Caught signal %d (SIGINT) — first Ctrl+C!\n", sig);
    printf("[Handler] Restoring default behavior with signal(SIGINT, SIG_DFL).\n");
    printf("[Handler] Next Ctrl+C will KILL the process.\n\n");
    signal(SIGINT, SIG_DFL);
}

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  One-shot signal handler (catch once, then default)\n");
    printf("══════════════════════════════════════\n\n");
    signal(SIGINT, custom_handler);

    printf("\n");
    printf("[Main PID %d] Custom SIGINT handler installed.\n", getpid());
    printf("  1st Ctrl+C → handler catches it, restores default\n");
    printf("  2nd Ctrl+C → default action (terminate process)\n\n");

    int count = 0;
    while (1) {
        printf("[Main PID %d] Running... (tick %d)\n", getpid(), ++count);
        sleep(2);
    }

    return 0;
}
$ gcc -o sig_once 04-sig_init_once.c
$ ./sig_once
Expected Outputclick Run to execute live
══════════════════════════════════════
  One-shot signal handler (catch once, then default)
══════════════════════════════════════


[Main PID 1004] Custom SIGINT handler installed.
  1st Ctrl+C → handler catches it, restores default
  2nd Ctrl+C → default action (terminate process)

[Main PID 1004] Running... (tick 1)
[Main PID 1004] Running... (tick 2)
^C
[Handler] Caught signal 2 (SIGINT) — first Ctrl+C!
[Handler] Restoring default behavior with signal(SIGINT, SIG_DFL).
[Handler] Next Ctrl+C will KILL the process.

[Main PID 1004] Running... (tick 3)
[Main PID 1004] Running... (tick 4)
[Main PID 1004] Running... (tick 5)
^C

[runs until stopped — the site stops it after 6s]
Runs until stopped — stops automatically after 6sCtrl+C at 2.5 s is handled and resets the handler; the second Ctrl+C at 6 s kills it (Killed by SIGINT).
8

Graceful Shutdown with a Flag

The handler only sets a volatile sig_atomic_t flag; main() finishes the current item, writes a last line and closes work.log. The site presses Ctrl+C after 2.5 s — open work.log in the Files panel.

04a-graceful-shutdown.c
/*
 * 04a-graceful-shutdown.c — The safe pattern: the handler only sets a flag
 *
 * Key concepts: volatile sig_atomic_t, keep handlers tiny, finish work and close files cleanly
 * Compile: gcc -o graceful 04a-graceful-shutdown.c
 * Run:     ./graceful        (press Ctrl+C — then open work.log in the Files panel)
 *
 * A handler can interrupt main() anywhere — even in the middle of fprintf(). Doing real work
 * inside it (printf, malloc, writing files) is unsafe. So the handler only sets a flag;
 * main() notices it, finishes the current item, writes a last line and closes the file.
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

volatile sig_atomic_t stop = 0;            // the only thing the handler touches

void on_sigint(int sig)
{
    (void)sig;
    stop = 1;
}

int main(void)
{
    FILE *log = fopen("work.log", "w");
    if (log == NULL) {
        perror("work.log");
        return EXIT_FAILURE;
    }
    signal(SIGINT, on_sigint);

    printf("[PID %d] writing work items to work.log — press Ctrl+C to stop\n", getpid());
    int item = 0;
    while (!stop) {
        item++;
        fprintf(log, "work item %d done\n", item);
        fflush(log);
        printf("  item %d\n", item);
        fflush(stdout);
        usleep(500000);                    // half a second per item
    }

    fprintf(log, "--- stopped by Ctrl+C after %d items, file closed cleanly ---\n", item);
    fclose(log);
    printf("\nCtrl+C received: finished item %d, wrote the last line, closed work.log.\n", item);
    return EXIT_SUCCESS;
}
$ gcc -o graceful 04a-graceful-shutdown.c
$ ./graceful
Expected Outputclick Run to execute live
[PID 1008] writing work items to work.log — press Ctrl+C to stop
  item 1
  item 2
  item 3
  item 4
  item 5
  item 6
^C
Ctrl+C received: finished item 6, wrote the last line, closed work.log.
9

Signal Handler Behavior

Exploring what happens when a signal arrives while another handler is already executing.

05-sighandler_behaviour.c
/*
 * 05-sighandler_behaviour.c — Signal handler behavior during blocking syscalls
 *
 * Key concepts: signal delivery interrupts sleep/scanf, handler re-registration
 * Compile: gcc -o handler 05-sighandler_behaviour.c
 * Run:     ./handler
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    // for getpid()
#include <signal.h>    // for signal(), SIGINT

void signal_handler(int sig) {
    printf("\n[Handler] Caught signal %d (SIGINT) — Ctrl+C pressed during scanf!\n", sig);
    printf("[Handler] Returning to scanf... (it may fail or resume depending on the OS)\n\n");
}

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Signal handler behavior during blocking syscalls\n");
    printf("══════════════════════════════════════\n\n");
    signal(SIGINT, signal_handler);

    printf("\n");
    printf("[Main PID %d] What happens when Ctrl+C arrives while scanf() is blocking?\n\n", getpid());
    printf("  Experiment:\n");
    printf("    1. Don't type anything yet\n");
    printf("    2. Press Ctrl+C to send SIGINT\n");
    printf("    3. Observe: does scanf resume or fail?\n\n");

    int number;
    printf("  Enter a number: ");
    fflush(stdout);

    if (scanf("%d", &number) == 1) {
        printf("\n[Main] scanf succeeded! You entered: %d\n", number);
    } else {
        printf("[Main] scanf returned 0 or EOF — the signal interrupted the read.\n");
        printf("[Main] This is why sigaction() with SA_RESTART is often preferred.\n");
    }
    printf("\n[Main] Program continues normally after scanf.\n");
    printf("\n========================================\n");

    return 0;
}
$ gcc -o sig_behave 05-sighandler_behaviour.c
$ ./sig_behave
Expected Outputclick Run to execute live
══════════════════════════════════════
  Signal handler behavior during blocking syscalls
══════════════════════════════════════


[Main PID 1030] What happens when Ctrl+C arrives while scanf() is blocking?

  Experiment:
    1. Don't type anything yet
    2. Press Ctrl+C to send SIGINT
    3. Observe: does scanf resume or fail?

  Enter a number: 5

[Main] scanf succeeded! You entered: 5

[Main] Program continues normally after scanf.

========================================
Asks for input — sample input is one click awayPress Ctrl+C while it waits for input to see what the handler does to scanf
10

sigaction vs signal

Comparing the behavior of sigaction() to signal() — why sigaction is the preferred, portable choice.

06-sigaction_behaviour.c
/*
 * 06-sigaction_behaviour.c — sigaction vs signal — comparing behavior during I/O
 *
 * Key concepts: sigaction struct, SA_RESTART flag, reliable signal handling
 * Compile: gcc -o sigact 06-sigaction_behaviour.c
 * Run:     ./sigact
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    // for getpid()
#include <signal.h>    // for sigaction(), SIGINT

void sigint_handler(int sig) {
    printf("\n[Handler] Caught signal %d (SIGINT) via sigaction!\n", sig);
    printf("[Handler] Unlike signal(), sigaction handlers are NOT reset automatically.\n\n");
}

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  sigaction vs signal\n");
    printf("══════════════════════════════════════\n\n");
    struct sigaction sa;
    sa.sa_handler = sigint_handler;
    sa.sa_flags = 0;              // No SA_RESTART — scanf will be interrupted
    sigemptyset(&sa.sa_mask);

    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("sigaction failed");
        exit(EXIT_FAILURE);
    }

    printf("\n");
    printf("[Main PID %d] Using sigaction() instead of signal().\n\n", getpid());
    printf("  Key differences from signal():\n");
    printf("    - Handler is NOT reset after first signal\n");
    printf("    - sa_flags controls restart behavior (SA_RESTART)\n");
    printf("    - sa_mask can block other signals during handler\n\n");
    printf("  Try: press Ctrl+C during scanf, then observe what happens.\n\n");

    int number;
    printf("  Enter a number: ");
    fflush(stdout);

    if (scanf("%d", &number) == 1) {
        printf("\n[Main] scanf succeeded! You entered: %d\n", number);
    } else {
        printf("[Main] scanf failed — signal interrupted the blocking read.\n");
        printf("[Main] With sa.sa_flags = SA_RESTART, scanf would have resumed.\n");
    }
    printf("\n[Main] Program continues normally.\n");
    printf("\n========================================\n");

    return 0;
}
$ gcc -o sigaction_cmp 06-sigaction_behaviour.c
$ ./sigaction_cmp
Expected Outputclick Run to execute live
══════════════════════════════════════
  sigaction vs signal
══════════════════════════════════════


[Main PID 1063] Using sigaction() instead of signal().

  Key differences from signal():
    - Handler is NOT reset after first signal
    - sa_flags controls restart behavior (SA_RESTART)
    - sa_mask can block other signals during handler

  Try: press Ctrl+C during scanf, then observe what happens.

  Enter a number: 5

[Main] scanf succeeded! You entered: 5

[Main] Program continues normally.

========================================
Asks for input — sample input is one click awayPress Ctrl+C while it waits for input — compare with the previous example

Open Full Terminal

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