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<stdio.h>
#include<signal.h>
#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
	signal(SIGINT,signal_handler);

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

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>
#include<string.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");
		sleep(2);
	}

	return 0;
}

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

Ref:

https://linux.die.net/man/3/sleep

https://linux.die.net/man/2/sigaction



Related Contents to follow