How to Prevent C program from getting killed with ctrl-c pressed, the program should not terminate. Ctrl+C is used to terminate process. Pressing Ctrl+C generates interrupt signal (SIGINT ) to a process.

To handle a linux signal in c or c++ program a process has to register the signal using signal(..) system call. For example in Below code the signal SIGINT ( interrupt ) is handled.

How to Prevent C program from getting killed with ctrl-c pressed

#include <unistd.h>

void signal_handler(int signum) {
	printf("Got an Cntr+C , continue..\n");

int main()
	// SIGINT would occur when Ctrl+c will be pressed

	while(1) {
		printf("Running .. process \n");

compile the code

#gcc -o sample sample.c

Run the sample on linux terminal and press Cntl+C ,, observer the output.

$ ./sample

Running .. process

Running .. process

^CGot an Cntr+C , continue..

Running .. process

Pressing Contrl+C would not terminate the process. The above method to handle Linux signal is deprecated. Let us write a simple c program using sigation system call.

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

static void handler(int sig, siginfo_t *siginfo, void *context) {
	printf("Got an interrupt ,ignore ..");

int main(int argc, char *argv[]) {
	struct sigaction handle;
	// initialize
	memset(&handle, '\0', sizeof(handle));

	/* Use the sa_sigaction field because the handles has two additional parameters */
	handle.sa_sigaction = &handler;

	/* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field*/
	handle.sa_flags = SA_SIGINFO;

	if (sigaction(SIGINT, &handle, NULL) < 0) {
		return 1;

	for (;;) {
		printf("Press Cntr-C and see the result \n");

	return 0;

The sigaction() system call is used to change the action taken by a process on receipt of a specific signal.


Related Contents to follow