C and C++ signal handling and C++ signal classes and examples

Signals:

Description: Signals are software interrupts delivered to a process by the operating system. Signals can also be issued by the operating system based on system or error conditions. There is a default behavior for some (i.e. a process is terminated when it receives an inturrupt SIGINT signal by pressing keystrokes ctrl-C) but this tutorial shows how to handle the signal by defining callback functions to manage the signal. Where possible, this allows one to close files and perform operations and react in a manner defined by the programmer.

Note that not all signals can be handled.

Types of signals:

SignalValueDescription
SIGHUP1Hangup (POSIX)
Report that user's terminal is disconnected. Signal used to report the termination of the controlling process.
SIGINT2Interrupt (ANSI)
Program interrupt. (ctrl-c)
SIGQUIT3Quit (POSIX)
Terminate process and generate core dump.
SIGILL4Illegal Instruction (ANSI)
Generally indicates that the executable file is corrupted or use of data where a pointer to a function was expected.
SIGTRAP5Trace trap (POSIX)
SIGABRT
SIGIOT
6Abort (ANSI)
IOT trap (4.2 BSD)
Process detects error and reports by calling abort
SIGBUS7BUS error (4.2 BSD)
Indicates an access to an invalid address.
SIGFPE8Floating-Point arithmetic Exception (ANSI).
This includes division by zero and overflow.The IEEE Standard for Binary Floating-Point Arithmetic (ANSI/IEEE Std 754-1985) defines various floating-point exceptions.
SIGKILL9Kill, unblockable (POSIX)
Cause immediate program termination.
Can not be handled, blocked or ignored.
SIGUSR110User-defined signal 1
SIGSEGV11Segmentation Violation (ANSI)
Occurs when a program tries to read or write outside the memory that is allocated for it by the operating system, dereferencing a bad or NULL pointer. Indicates an invalid access to valid memory.
SIGUSR212User-defined signal 2
SIGPIPE13Broken pipe (POSIX)
Error condition like trying to write to a socket which is not connected.
SIGALRM14Alarm clock (POSIX)
Indicates expiration of a timer. Used by the alarm() function.
SIGTERM15Termination (ANSI)
This signal can be blocked, handled, and ignored. Generated by "kill" command.
SIGSTKFLT16Stack fault
SIGCHLD
SIGCLD
17Child status has changed (POSIX)
Signal sent to parent process whenever one of its child processes terminates or stops.
See the YoLinux.com Fork, exec, wait, waitpid tutorial
SIGCONT18Continue (POSIX)
Signal sent to process to make it continue.
SIGSTOP19Stop, unblockable (POSIX)
Stop a process. This signal cannot be handled, ignored, or blocked.
SIGTSTP20Keyboard stop (POSIX)
Interactive stop signal. This signal can be handled and ignored. (ctrl-z)
SIGTTIN21Background read from tty (POSIX)
SIGTTOU22Background write to tty (POSIX)
SIGURG23Urgent condition on socket (4.2 BSD)
Signal sent when "urgent" or out-of-band data arrives on a socket.
SIGXCPU24CPU limit exceeded (4.2 BSD)
SIGXFSZ25File size limit exceeded (4.2 BSD)
SIGVTALRM26Virtual Time Alarm (4.2 BSD)
Indicates expiration of a timer.
SIGPROF27Profiling alarm clock (4.2 BSD)
Indicates expiration of a timer. Use for code profiling facilities.
SIGWINCH28Window size change (4.3 BSD, Sun)
SIGIO
SIGPOLL
29I/O now possible (4.2 BSD)
Pollable event occurred (System V)
Signal sent when file descriptor is ready to perform I/O (generated by sockets)
SIGPWR30Power failure restart (System V)
SIGSYS31Bad system call
See: /usr/include/bits/signum.h

Signals which can be processed include: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP

List all signals available to the system:

Use the command: kill -l

$ kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL
 5) SIGTRAP      6) SIGABRT      7) SIGBUS       8) SIGFPE
 9) SIGKILL     10) SIGUSR1     11) SIGSEGV     12) SIGUSR2
13) SIGPIPE     14) SIGALRM     15) SIGTERM     17) SIGCHLD
18) SIGCONT     19) SIGSTOP     20) SIGTSTP     21) SIGTTIN
22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO
30) SIGPWR      31) SIGSYS      34) SIGRTMIN    35) SIGRTMIN+1
36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4  39) SIGRTMIN+5
40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8  43) SIGRTMIN+9
44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13
52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9
56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6  59) SIGRTMAX-5
60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2  63) SIGRTMAX-1
64) SIGRTMAX

Sending a process a signal:

A process can be sent a signal using the "kill" command: kill -s signal-number pid

Where the pid (process id) can be obtained using the "ps" command.


C Signal handler and Example:

Basic C signal callback function example:

File: signalExample.cpp

01#include <stdio.h>
02#include <stdlib.h>
03#include <signal.h>
04
05// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
06void
07 signal_callback_handler(int signum)
08{
09 printf("Caught signal %d/n",signum);
10 // Cleanup and close up stuff here
11
12 // Terminate program
13 exit(signum);
14}
15
16 int main()
17{
18 // Register signal and signal handler
19 signal(SIGINT, signal_callback_handler);
20
21 while(1)
22 {
23 printf("Program processing stuff here./n");
24 sleep(1);
25 }
26 return EXIT_SUCCESS;
27}
Example to handle ctrl-c
Compile: gcc signalExample.cpp
Run: a.out
Results:
Program processing stuff here.
Program processing stuff here.
Caught signal 2

The function prototype: void (*signal (int sig, void (*func)(int)))(int);


C++ Signal Registration and Handling Class:

File: signalHandler.hpp

01#ifndef __SIGNALHANDLER_H__
02#define __SIGNALHANDLER_H_
03#include <stdexcept>
04 using std::runtime_error
05
06 class SignalException : public runtime_error
07{
08 public:
09 SignalException(const std::string& _message)
10 : std::runtime_error(_message)
11 {}
12};
13
14 class SignalHandler
15{
16 protected:
17 static bool mbGotExitSignal;
18
19 public:
20 SignalHandler();
21 ~SignalHandler();
22
23 static bool gotExitSignal();
24 static void setExitSignal(bool _bExitSignal);
25
26 void setupSignalHandlers();
27 static void exitSignalHandler(int _ignored);
28
29};
30#endif

File: signalHandler.cpp

01#include <signal.h>
02#include <errno.h>
03
04#include "signalHandler.hpp
05
06 bool SignalHandler::mbGotExitSignal = false;
07
08/**
09* Default Contructor.
10*/
11SignalHandler::SignalHandler()
12{
13}
14
15/**
16* Destructor.
17*/
18SignalHandler::~SignalHandler()
19{
20}
21
22/**
23* Returns the bool flag indicating whether we received an exit signal
24* @return Flag indicating shutdown of program
25*/
26 bool SignalHandler::gotExitSignal()
27{
28 return mbGotExitSignal;
29}
30
31/**
32* Sets the bool flag indicating whether we received an exit signal
33*/
34 void SignalHandler::setExitSignal(bool _bExitSignal)
35{
36 mbGotExitSignal = _bExitSignal;
37}
38
39/**
40* Sets exit signal to true.
41* @param[in] _ignored Not used but required by function prototype
42* to match required handler.
43*/
44 void SignalHandler::exitSignalHandler(int _ignored)
45{
46 mbGotExitSignal = true;
47}
48
49/**
50* Set up the signal handlers for CTRL-C.
51*/
52 void SignalHandler::setupSignalHandlers()
53{
54 if (signal((int) SIGINT, SignalHandler::exitSignalHandler) == SIG_ERR)
55 {
56 throw SignalException("!!!!! Error setting up signal handlers !!!!!");
57 }
58}

File: test.cpp

01#include <iostream>
02#include "signalHandle.hpp"
03 using namespace std;
04
05main()
06{
07 int iret;
08
09 try
10 {
11 SignalHandler signalHandler;
12
13 // Register signal handler to handle kill signal
14 signalHandler.setupSignalHandlers();
15
16 // Infinite loop until signal ctrl-c (KILL) received
17 while(!signalHandler.gotExitSignal())
18 {
19 sleep(1);
20 }
21
22 iret = EXIT_SUCCESS;
23 }
24 catch (SignalException& e)
25 {
26 std::cerr << "SignalException: " << e.what() << std::endl;
27 iret = EXIT_FAILURE;
28 }
29 return(iret);
30}

Compile: g++ signalHandle.cpp test.cpp


C Signal Man Pages:

C functions:

  • signal - ANSI C signal handling
  • raise - send a signal to the current process
  • strsignal - return string describing signal (GNU extension)
  • psignal - print signal message
  • sigaction - POSIX signal handling functions
  • sigsetops - POSIX signal set operations
  • sigvec - BSD software signal facilities
  • alarm - set an alarm clock for delivery of a signal

Commands:

  • kill - terminate a process
  • ps - report a snapshot of the current processes.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值