← Back to C Course | Chapter 14: Additional Topics | Lesson 6 of 9

C Signal Handling

What is a Signal?

A signal is an asynchronous notification the operating system delivers to a running process to report an event like an illegal instruction, a segmentation fault, or the user pressing Ctrl+C, interrupting the program's normal flow so it can react to that event.

Example: What is a Signal?

c
#include <stdio.h>
#include <signal.h>
int main() {
	printf("Signals notify a process of events like Ctrl+C");
	return 0;
}

The signal() Function

The signal() function registers a custom handler function to run whenever a specific signal (identified by a constant like SIGINT or SIGSEGV) is delivered to your process, letting you replace the operating system's default behavior — which is usually to terminate the program outright — with your own response.

Example: The signal() Function

c
#include <stdio.h>
#include <signal.h>
void handler(int sig) {
	printf("Caught signal %d", sig);
}
int main() {
	signal(SIGINT, handler);
	raise(SIGINT);
	return 0;
}

Catching SIGINT

SIGINT is the signal generated when the user presses Ctrl+C in the terminal running your program, and catching it with a custom handler lets your program close open files, free resources, and shut down gracefully instead of being killed abruptly mid-operation.

Example: Catching SIGINT

c
#include <stdio.h>
#include <signal.h>
void handleSigint(int sig) {
	printf("Ctrl+C caught, cleaning up");
}
int main() {
	signal(SIGINT, handleSigint);
	raise(SIGINT);
	return 0;
}

Ignoring Signals

Passing the special value SIG_IGN as the handler argument to signal() tells the operating system to simply discard a specific signal whenever it arrives, rather than acting on it — a way to make a section of your program deliberately immune to an interrupt like SIGINT.

Example: Ignoring Signals

c
#include <stdio.h>
#include <signal.h>
int main() {
	signal(SIGINT, SIG_IGN);
	printf("SIGINT will now be ignored");
	return 0;
}

Raising Signals with raise()

The raise() function lets a program generate and send a signal to itself programmatically, which is useful for testing how your own signal handlers behave, or for deliberately triggering an internal fault-handling path from within the program's own logic.

Example: Raising Signals with raise()

c
#include <stdio.h>
#include <signal.h>
void handler(int sig) {
	printf("Handler triggered by raise()");
}
int main() {
	signal(SIGTERM, handler);
	raise(SIGTERM);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.