Signals exampe, sigaction included

This commit is contained in:
Imbus 2025-08-28 14:45:30 +02:00
parent f3522129a3
commit 080928d3fd
3 changed files with 64 additions and 0 deletions

24
signals/Makefile Normal file
View file

@ -0,0 +1,24 @@
CC ?= gcc
CFLAGS ?= -Wall -O2
# This is not how makefiles should be written.
# Pretend you did not see this
all: main.elf main_sigaction.elf
TARGET = main.elf
SRC = main.c
TARGET2 = main_sigaction.elf
SRC2 = main_sigaction.c
$(TARGET): $(SRC)
@echo CC $@
@$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
$(TARGET2): $(SRC2)
@echo CC $@
@$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
clean:
rm -f *.elf

17
signals/main.c Normal file
View file

@ -0,0 +1,17 @@
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void handler(int sig) {
printf("Caught signal %d\n", sig);
exit(1);
}
int main() {
signal(SIGINT, handler); // Handle Ctrl+C
while (1) {
printf("Running...\n");
sleep(1);
}
}

23
signals/main_sigaction.c Normal file
View file

@ -0,0 +1,23 @@
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void handler(int sig) {
write(1, "Caught SIGINT\n", 14); // Async-signal-safe output
exit(1);
}
int main() {
struct sigaction sa;
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
while (1) {
printf("Running...\n");
sleep(1);
}
}