Applied signal programming bringing together fork, exec, and signals. Includes a two-program alarm management system, parent-child coordination using signals, and multiplexing signals across four child processes.
The child program that handles alarm signals — launched by the alarm manager via exec.
alarm_manager/alarm_handler.c45 lines
/* * alarm_handler.c — Alarm handler child (executed by alarm_manager) * * Key concepts: Child process that handles SIGALRM, called via exec * Compile: gcc -o alarm_handler alarm_handler.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <string.h>#include <sys/types.h>int main(int argc, char *argv[]) { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Alarm Handler (Child Process)\n"); printf("══════════════════════════════════════\n\n"); if (argc != 3) { fprintf(stderr, "Usage: %s <seconds> <parent_pid>\n", argv[0]); exit(EXIT_FAILURE); } int seconds = atoi(argv[1]); pid_t parent_pid = atoi(argv[2]); printf("[Handler PID %d] Will sleep %d seconds, then signal parent PID %d\n", getpid(), seconds, parent_pid); fflush(stdout); // Sleep for the specified number of seconds sleep(seconds); // Send SIGUSR1 to the parent process if (kill(parent_pid, SIGUSR1) == -1) { perror("[Handler] Failed to send SIGUSR1 to parent"); exit(EXIT_FAILURE); } printf("[Handler PID %d] Sent SIGUSR1 to parent PID %d after %d seconds.\n", getpid(), parent_pid, seconds); return 0;}
Editing — changes sent to terminal on Run
Reference — not run on its ownStarted by alarm_manager.c with exec — run that example.
2
Alarm Manager (Parent)
A parent program that forks and execs the alarm handler, then coordinates alarm scheduling across processes.
alarm_manager/alarm_manager.c135 lines
/* * alarm_manager.c — Alarm manager parent — fork+exec based alarm system * * Key concepts: fork, exec, multi-process signal coordination * Compile: gcc -o alarm_manager alarm_manager.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <string.h>#include <sys/wait.h>// this program is a simple alarm manager// it will set an alarm for the specified number of seconds// and when the alarm is triggered, it will print a message// and ask for another alarm to be set// for each alarm, a child process is created// and the child process will send a signal to the parent process// when the alarm is triggered//to exit just type exit//otherwise type the number of seconds to set new alarm#define MAX_ALARMS 10int alarm_count = 0;// Signal handler for SIGUSR1void handle_alarm(int sig) { alarm_count++; printf("\n[ALARM #%d] Signal %d received — a child timer fired!\n", alarm_count, sig); printf("myalarm> "); fflush(stdout);}int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Alarm Manager (fork + exec)\n"); printf(" Each alarm spawns a child process\n"); printf("══════════════════════════════════════\n\n"); pid_t pid; char input[100]; struct sigaction sa; // Setup signal handler sa.sa_handler = handle_alarm; //WHAT WILL HAPPEND IF WE DONT USE SA_RESTART HERE? sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); if (sigaction(SIGUSR1, &sa, NULL) == -1) { perror("sigaction"); exit(EXIT_FAILURE); } printf("[Parent PID %d] Alarm Manager ready.\n", getpid()); printf("[Info] Type seconds to set an alarm, 'exit' to quit.\n"); printf("[Info] Each alarm forks a child that sleeps, then signals back.\n\n"); while (1) { printf("myalarm> "); /* fflush(stdout) is used after the printf("myalarm> "); statement to ensure that the prompt myalarm> is displayed to the user right away, without waiting for the buffer to fill up or for a newline character to be encountered. */ fflush(stdout); if (fgets(input, sizeof(input), stdin) == NULL) { break; } // Remove newline character //why this works? because fgets reads the newline character // and strcspn returns the number of characters before the newline // so the position of the newline is the number of characters before it // and we replace it with a null terminator input[strcspn(input, "\n")] = '\0'; if (strcmp(input, "exit") == 0) { printf("Exiting Alarm Manager.\n"); break; } int seconds = atoi(input); if (seconds <= 0) { printf("Please enter a valid number of seconds.\n"); continue; } // Fork a child process pid = fork(); if (pid < 0) { perror("Fork failed"); continue; } if (pid == 0) { // Child process: Execute the alarm handler char seconds_str[10]; char parent_pid_str[10]; snprintf(seconds_str, sizeof(seconds_str), "%d", seconds); snprintf(parent_pid_str, sizeof(parent_pid_str), "%d", getppid()); execlp("./alarm_handler", "./alarm_handler", seconds_str, parent_pid_str, (char *)NULL); //you can also do int status = execlp("./alarm_handler", "./alarm_handler", seconds_str, parent_pid_str, (char *)NULL); // if execlp returned, its means it failed, so we can perror and exit perror("execlp failed"); exit(EXIT_FAILURE); } else { // Parent process: Continue to accept more alarms printf("[Parent] Forked child PID %d — alarm set for %d seconds.\n", pid, seconds); } } //make sure we wait on all the children so we dont have zombies //even if all the children are done, we still need to wait while (wait(NULL) > 0); return 0;}
══════════════════════════════════════
Alarm Manager (fork + exec)
Each alarm spawns a child process
══════════════════════════════════════
[Parent PID 1558] Alarm Manager ready.
[Info] Type seconds to set an alarm, 'exit' to quit.
[Info] Each alarm forks a child that sleeps, then signals back.
myalarm> 2
exit
[Parent] Forked child PID 1569 — alarm set for 2 seconds.
myalarm> Exiting Alarm Manager.
══════════════════════════════════════
Alarm Handler (Child Process)
══════════════════════════════════════
[Handler PID 1569] Will sleep 2 seconds, then signal parent PID 1558
[Handler PID 1569] Sent SIGUSR1 to parent PID 1558 after 2 seconds.
[ALARM #1] Signal 10 received — a child timer fired!
myalarm> student:~$
Asks for input — sample input is one click away
3
Parent-Child Coordination
Parent and child synchronize execution using SIGUSR1 and SIGUSR2, taking turns in a controlled sequence.
coordination.c115 lines
/* * coordination.c — Parent-child signal coordination — synchronized printing * * Key concepts: kill(), SIGUSR1, parent and child take turns via signals * Compile: gcc -o coord coordination.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <string.h>#include <sys/wait.h>// Global variables to store child PIDspid_t child1_pid = 0;pid_t child2_pid = 0;volatile sig_atomic_t all_done = 0; // set by the SIGUSR2 handler so main can stop waiting// Function to set up signal handlers using sigactionvoid setup_sigaction(int signum, void (*handler)(int)) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); if (sigaction(signum, &sa, NULL) == -1) { perror("Failed to set up sigaction"); exit(EXIT_FAILURE); }}// Signal handler for SIGUSR1 (from Child 1)void handle_sigusr1(int signum) { printf("\n[Parent] Received SIGUSR1 from Child 1 — task acknowledged.\n"); printf("[Parent] Sending SIGUSR2 to Child 2 (PID %d) to start its task...\n", child2_pid); if (kill(child2_pid, SIGUSR2) == -1) { perror("[Parent] Failed to send SIGUSR2 to Child 2"); }}// Signal handler for SIGUSR2 (from Child 2)void handle_sigusr2(int signum) { printf("\n[Parent] Received SIGUSR2 from Child 2 — all tasks completed!\n"); printf("[Parent] Terminating both children...\n"); kill(child1_pid, SIGTERM); kill(child2_pid, SIGTERM); all_done = 1;}// Child 2 needs a handler (even an empty one): with SIG_DFL, SIGUSR2 would kill it instead of waking pause()void child_wakeup(int signum) { (void)signum;}int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Parent-Child Signal Coordination\n"); printf(" Child1 → Parent → Child2 → Parent\n"); printf("══════════════════════════════════════\n\n"); // Set up the signal handlers in the parent using sigaction setup_sigaction(SIGUSR1, handle_sigusr1); setup_sigaction(SIGUSR2, handle_sigusr2); printf("[Parent PID %d] Signal handlers registered.\n\n", getpid()); // Fork Child 1 child1_pid = fork(); if (child1_pid < 0) { perror("Failed to fork Child 1"); exit(EXIT_FAILURE); } if (child1_pid == 0) { // In Child 1 printf("[Child 1 PID %d] Started. Working for 2 seconds...\n", getpid()); sleep(2); printf("[Child 1 PID %d] Done! Sending SIGUSR1 to Parent (PID %d).\n", getpid(), getppid()); kill(getppid(), SIGUSR1); pause(); exit(0); } // Fork Child 2 child2_pid = fork(); if (child2_pid < 0) { perror("Failed to fork Child 2"); kill(child1_pid, SIGTERM); exit(EXIT_FAILURE); } if (child2_pid == 0) { // In Child 2 printf("[Child 2 PID %d] Started. Waiting for signal from Parent...\n", getpid()); setup_sigaction(SIGUSR2, child_wakeup); pause(); printf("[Child 2 PID %d] Received signal! Task done. Sending SIGUSR2 to Parent.\n", getpid()); kill(getppid(), SIGUSR2); exit(0); } printf("[Parent] Forked Child 1 (PID %d) and Child 2 (PID %d).\n", child1_pid, child2_pid); printf("[Parent] Waiting for Child 1 to finish its work...\n\n"); while (!all_done) { pause(); // Wait for signals until Child 2 reports back } //wait on all the children while (wait(NULL) > 0); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o coordination coordination.c
$ ./coordination
Expected Outputclick Run to execute live
══════════════════════════════════════
Parent-Child Signal Coordination
Child1 → Parent → Child2 → Parent
══════════════════════════════════════
[Parent PID 1565] Signal handlers registered.
[Child 1 PID 1566] Started. Working for 2 seconds...
[Parent] Forked Child 1 (PID 1566) and Child 2 (PID 1567).
[Child 2 PID 1567] Started. Waiting for signal from Parent...
[Parent] Waiting for Child 1 to finish its work...
[Child 1 PID 1566] Done! Sending SIGUSR1 to Parent (PID 1565).
[Parent] Received SIGUSR1 from Child 1 — task acknowledged.
[Parent] Sending SIGUSR2 to Child 2 (PID 1567) to start its task...
[Child 2 PID 1567] Received signal! Task done. Sending SIGUSR2 to Parent.
[Parent] Received SIGUSR2 from Child 2 — all tasks completed!
[Parent] Terminating both children...
4
Signals Across 4 Children
A parent process that forks four children and coordinates them by sending different signals to each.
multiply_signals.c136 lines
/* * multiply_signals.c — Multiplexing signals across 4 child processes * * Key concepts: Multiple children, signal routing, wait, kill * Compile: gcc -o multi_sig multiply_signals.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <signal.h>#include <string.h>#include <sys/wait.h>// Number of child processes#define NUM_CHILDREN 4// Function prototypes for signal handlersvoid handle_sigint(int sig);void handle_sigusr1(int sig);void handle_sigusr2(int sig);void handle_sigterm(int sig);int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Signal Multiplexing — 4 Children\n"); printf(" Each child sends a different signal\n"); printf("══════════════════════════════════════\n\n"); pid_t pid; struct sigaction sa_int, sa_usr1, sa_usr2, sa_term; // Setting up SIGINT handler sa_int.sa_handler = handle_sigint; sa_int.sa_flags = 0; sigemptyset(&sa_int.sa_mask); if (sigaction(SIGINT, &sa_int, NULL) == -1) { perror("Error: cannot handle SIGINT"); exit(EXIT_FAILURE); } // Setting up SIGUSR1 handler sa_usr1.sa_handler = handle_sigusr1; sa_usr1.sa_flags = 0; sigemptyset(&sa_usr1.sa_mask); if (sigaction(SIGUSR1, &sa_usr1, NULL) == -1) { perror("Error: cannot handle SIGUSR1"); exit(EXIT_FAILURE); } // Setting up SIGUSR2 handler sa_usr2.sa_handler = handle_sigusr2; sa_usr2.sa_flags = 0; sigemptyset(&sa_usr2.sa_mask); if (sigaction(SIGUSR2, &sa_usr2, NULL) == -1) { perror("Error: cannot handle SIGUSR2"); exit(EXIT_FAILURE); } // Setting up SIGTERM handler sa_term.sa_handler = handle_sigterm; sa_term.sa_flags = 0; sigemptyset(&sa_term.sa_mask); if (sigaction(SIGTERM, &sa_term, NULL) == -1) { perror("Error: cannot handle SIGTERM"); exit(EXIT_FAILURE); } printf("[Parent PID %d] Handlers registered for SIGINT, SIGUSR1, SIGUSR2, SIGTERM.\n\n", getpid()); // Array of signals to be sent by children const char *sig_names[NUM_CHILDREN] = {"SIGINT", "SIGUSR1", "SIGUSR2", "SIGTERM"}; int signals[NUM_CHILDREN] = {SIGINT, SIGUSR1, SIGUSR2, SIGTERM}; // Forking child processes for (int i = 0; i < NUM_CHILDREN; i++) { pid = fork(); if (pid < 0) { perror("Fork failed"); exit(EXIT_FAILURE); } if (pid == 0) { // Child process int delay = 2 * (i + 1); printf("[Child %d PID %d] Will send %s in %d seconds.\n", i, getpid(), sig_names[i], delay); fflush(stdout); sleep(delay); printf("[Child %d PID %d] Sending %s to Parent (PID %d)...\n", i, getpid(), sig_names[i], getppid()); if (kill(getppid(), signals[i]) == -1) { perror("Failed to send signal"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } } // Parent process waits for signals indefinitely printf("\n[Parent] All children forked. Waiting for signals...\n"); printf("[Parent] Signals will arrive staggered: 2s, 4s, 6s, 8s.\n\n"); while (1) { pause(); // Wait for signals } // // This point is never reached return 0;}// Handler for SIGINTvoid handle_sigint(int sig) { printf("\n[Handler] SIGINT (signal %d) — Interrupt. Handling gracefully.\n\n", sig);}void handle_sigusr1(int sig) { printf("[Handler] SIGUSR1 (signal %d) — User-defined signal 1 received.\n\n", sig);}void handle_sigusr2(int sig) { printf("[Handler] SIGUSR2 (signal %d) — User-defined signal 2 received.\n\n", sig);}void handle_sigterm(int sig) { printf("[Handler] SIGTERM (signal %d) — Termination. Cleaning up...\n", sig); // Perform any necessary cleanup here //before exiting, we need to wait for all the children to finish //we can do that by using the wait function while (wait(NULL) > 0); // Wait for all child processes to finish exit(EXIT_SUCCESS);}
Editing — changes sent to terminal on Run
$ gcc -o multi_sig multiply_signals.c
$ ./multi_sig
Expected Outputclick Run to execute live
══════════════════════════════════════
Signal Multiplexing — 4 Children
Each child sends a different signal
══════════════════════════════════════
[Parent PID 1609] Handlers registered for SIGINT, SIGUSR1, SIGUSR2, SIGTERM.
[Child 0 PID 1610] Will send SIGINT in 2 seconds.
[Child 1 PID 1611] Will send SIGUSR1 in 4 seconds.
[Child 2 PID 1612] Will send SIGUSR2 in 6 seconds.
[Parent] All children forked. Waiting for signals...
[Parent] Signals will arrive staggered: 2s, 4s, 6s, 8s.
[Child 3 PID 1613] Will send SIGTERM in 8 seconds.
[Child 0 PID 1610] Sending SIGINT to Parent (PID 1609)...
[Handler] SIGINT (signal 2) — Interrupt. Handling gracefully.
[Child 1 PID 1611] Sending SIGUSR1 to Parent (PID 1609)...
[Handler] SIGUSR1 (signal 10) — User-defined signal 1 received.
[Child 2 PID 1612] Sending SIGUSR2 to Parent (PID 1609)...
[Handler] SIGUSR2 (signal 12) — User-defined signal 2 received.
[Child 3 PID 1613] Sending SIGTERM to Parent (PID 1609)...
[Handler] SIGTERM (signal 15) — Termination. Cleaning up...
Open Full Terminal
Get a Linux terminal with all 4 files from this lesson pre-loaded. Compile, run, and experiment freely.