codescracker


c++

C++ Signal Handling



« Previous Tutorial Next Tutorial »


Signals handling in C++, allows you to handle the signal that are the interrupts delivered to a process by the OS, that can possibly terminate your program prematurely.

C++ Signal Handling Example Program

Here is an example program demonstrating signal handling in C++

/* C++ Signal Handling - Example Program */

#include<iostream.h>
#include<signal.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>
void signalhandler(int sn)
{
	cout<<"Interrupt signal ("<<sn<<") received\n";
	exit(sn);
}
void main()
{
	clrscr();
	signal(SIGINT, signalhandler);
	while(1)
	{
		cout<<"Going for sleep...\n";
		sleep(1);
	}
	getch();
}

Here is the sample output of the above C++ program:

Going for sleep...
Going for sleep...
Going for sleep...

Press CTRL+C to interrupt the above program and you will see that your program will catch the signal and would come out by printing like this:

Going for sleep...
Going for sleep...
Going for sleep...
Interrupt signal (2) received

Let's take another C++ program, also demonstrating signal handling in C++

/* C++ Signal Handling - Example Program */

#include<iostream.h>
#include<conio.h>
#include<dos.h>
#include<signal.h>
#include<stdlib.h>
void signalhandler(int sn)
{
	cout<<"Interrupt signal ("<<sn<<") received\n";
	exit(sn);
}
void main()
{
	clrscr();
	int a=0;
	signal(SIGINT, signalhandler);
	while(++a)
	{
		cout<<"Going for sleep...\n";
		if(a==3)
		{
			raise(SIGINT);
		}
		sleep(1);
	}
	getch();
}

Here is the output produced by the above C++ program:

Going for sleep...
Going for sleep...
Going for sleep...
Interrupt signal (2) received

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test