Learn Basic C++ Signal Handling Tutorials and Examples

C++ Signal Handling are the interrupts in a process causing the operating system to end a program suddenly. These interrupts are applied by pressing Ctrl+C on UNIX, LINUX, Mac OS X, and Windows systems.

Signal & Description

Signals are interruptions that cause an OS to interrupt the program its work in order to attend to another ongoing task. As a result, the signals handle interrupts in order to stop these activities. The language provides signals in C++.

It detects the interrupting signal and resolves the issue that causes the program to pause while performing its function. The C++ signal library contains signals that a developer can work with, and here are their definitions:

SignalDefinition
SIGABRT (Signal Abort)It is an abnormal program termination, such as an abort command. The program applies this signal in the event of fatal errors.
SIGFPE (Signal: Floating-Point Exception)This signal indicates a fatal calculation error. Even though its name comes from the phrase “floating-point exception,” this signal covers all math mistakes, such as division by zero and overflow.
SIGSTOP (Signal Stop)This signal automatically terminates and prevents any interruption from occurring in a process.
SIGCONT (Signal Continue)After blocking or terminating an interrupt, this signal enables the running process to resume.
SIGTRAP (Signal Trap)This signal tracks all traps (exceptions) and asks for the current process to end.
SIGQUIT (Signal Quit)It generates a core dump that terminates the interrupt.
SIGILL (Signal Illegal Instruction)This signal stops a command or instruction that shouldn’t be there, like an interruption.
SIGINT (Signal Interrupt)It enables the receiver end to generate an interactive attention signal as a “program interrupt. This C++ signal stops an interruption from the OS so that the current job can proceed.
SIGTERM (Signal Termination)This signal comes from the kill command and generates a request to terminate the interrupt in a running application. The incoming signal is cut off before it arrives, so it won’t disturb the current job.
SIGBUS (Signal Bus)This signal informs the running software that there’s a BUS error, attempting to reach an incorrect address, and terminates the program.
SIGALRM (Signal Alarm)This signal lets you know that you are trying to access an invalid address by using an alarm feature.
SIGSEGV (Signal Segmentation Violation)The signal displays and manages interrupts as invalid storage access.
SIGHUP (Signal Hang Up)This signal notifies a process that is controlling terminal interruption.
SIGUSR1 (Signal User 1) SIGSUR2 (Signal User 1)These are signals for users’ discretionary use, in short, user-defined terms.
C++ Signal Library

Signal() Function in C++

In C++, the signal() function establishes the error handler for the signal given. Here’s an example syntax of the signal() function:

void (*signal (int sig, void (*func)(int)))(int);

Learn more about C++ syntax through our complete C++ Basic Syntax Tutorial.

How C++ signal() Handling functions work

The signal() functions in C++ follow a sequence of procedures that work to achieve the intended result. First, notice that all signal functions have two arguments, and both are very important.

signal(registered signal, signal handler);

In the first parameter, the registered signal and integer are related to the signal method. The second parameter, the signal handler, is in charge of catching all interruptions and exceptions through C++ signals.

Upon delivered to a process signal functions, the function will produce an output. Its output will need to make an interruption stand out, so the signal used to catch them will print them.

After the procedure, another function known as the raise function is included. This method evaluates the first parameter and registers signals to the program that is presently executing. Invoking a function produces the required signal.

Take note: The following are included in Signal() Function.

Prototypes

This signal function is defined in a <csignal> header file and defines a signal processing approach. The function allows the handler to configure or conduct any of the following actions:

  • Handling a signal by default.
  • Ignoring the signal to handle it.
  • Handle it using a user-defined function.

Parameters

The components of this signal function are sig and handler. sig is the signal that is handled by the signal handler. It could be any one of the following signals:

  • SIGABRT
  • SIGFPE
  • SIGILL
  • SIGINT Signal
  • SIGTERM
  • etc.

The signal must be formatted as follows:

void fun(int sig);

Return Value

Return Value is the value returned when the function’s input request is successful or unsuccessful. If successful, the function returns to the signal handler responsible for the command. However, if it fails, SIG ERR is returned.

Example Signal() Function in C++

This is the value returned when the function’s input request is successful or unsuccessful. If successful, the function returns to the signal handler responsible for the command. However, if it fails, SIG ERR is returned.

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signame) {
   cout << "Interrupt signal (" << signame<< ") received.\n";

   exit(signame);  
}

int main () {

   signal(SIGINT, signalHandler);  

   while(1) {
      cout << "It's ok" << endl;
      sleep(1);
   }

   return 0;
}

Upon compilation and execution of the preceding codes, it will produce an infinite loop:

It's ok
It's ok
It's ok

Now, press Ctrl+C to stop the program. You’ll see that your application will recognize the signal and print the following:

It's ok
It's ok
It's ok
Interrupt signal (2) received.

Raise() Function in C++

In C++, raise() is a function that generates signals and takes an integer signal number as an argument. It has the example syntax:

int raise (signal sig);

In this example, the sig is the signal number sent in any of the signals, such as SIGABRT, SIGFPE, SIGILL, SIGINT, SIGTERM, etc.,

Here’s an example of how we use the raise() function to send an internal signal.

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signum ) {
   cout << "Interrupt signal (" << signum << ") received.\n";

   exit(signum);  
}

int main () {
   int i = 0;

   signal(SIGINT, signalHandler);  

   while(++i) {
      cout << "It's ok" << endl;
      if( i == 3 ) {
         raise( SIGINT);
      }
      sleep(1);
   }

   return 0;
}

This example code will automatically display the following output:

It's ok
It's ok
It's ok
Interrupt signal (2) received.

Remember, the signal() function registers a condition handler while raise() causes the condition to be raised. You can ignore the condition using the signal() function. In contrast, the Raise() function is able to transmit signals to the program.

Conclusion

In conclusion, we have learned the Basic C++ Signal Handling Function, its type, description, and examples. Learning how to handle basic C++ signals can improve your programming skills.

The very purpose of handling C++ signals is to trap of send an interruptions in C++ programs. As a result, the signal() and raise() function sets the error handler for the specified interruption.

Leave a Comment