The Wayback Machine - https://web.archive.org/web/20240814020738/https://www.geeksforgeeks.org/signals-c-language/
Open In App

Signals in C language

Last Updated : 08 Feb, 2018
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow


Prerequisite : Fork system call, Wait system call
A signal is a software generated interrupt that is sent to a process by the OS because of when user press ctrl-c or another process tell something to this process.
There are fix set of signals that can be sent to a process. signal are identified by integers.
Signal number have symbolic names. For example SIGCHLD is number of the signal sent to the parent process when child terminates.
Examples:

#define SIGHUP  1   /* Hangup the process */ 
#define SIGINT  2   /* Interrupt the process */ 
#define SIGQUIT 3   /* Quit the process */ 
#define SIGILL  4   /* Illegal instruction. */ 
#define SIGTRAP 5   /* Trace trap. */ 
#define SIGABRT 6   /* Abort. */

OS Structures for Signals

  • For each process, the operating system maintains 2 integers with the bits corresponding to a signal numbers.
  • The two integers keep track of: pending signals and blocked signals
  • With 32 bit integers, up to 32 different signals can be represented.

Example :
In the example below, the SIGINT ( = 2) signal is blocked and no signals are pending.

A signal is sent to a process setting the corresponding bit in the pending signals integer for the process. Each time the OS selects a process to be run on a processor, the pending and blocked integers are checked. If no signals are pending, the process is restarted normally and continues executing at its next instruction.

If 1 or more signals are pending, but each one is blocked, the process is also restarted normally but with the signals still marked as pending. If 1 or more signals are pending and NOT blocked, the OS executes the routines in the process’s code to handle the signals.

Default Signal Handlers

There are several default signal handler routines. Each signal is associated with one of these default handler routine. The different default handler routines typically have one of the following actions:

  • Ign: Ignore the signal; i.e., do nothing, just return
  • Term: terminate the process
  • Cont: unblock a stopped process
  • Stop: block the process




// CPP program to illustrate
// default Signal Handler
#include<stdio.h>
#include<signal.h>
  
int main()
{
    signal(SIGINT, handle_sigint);
    while (1)
    {
        printf(“hello world\n”);
        sleep(1);
    }
    return 0;
}


Output: Print hello world infinite times. If user presses ctrl-c to terminate the process because of SIGINT signal sent and its default handler to terminate the process.

hello world   
hello world         
hello world         
terminated          

User Defined Signal Handlers

A process can replace the default signal handler for almost all signals (but not SIGKILL) by its user’s own handler function.
A signal handler function can have any name, but must have return type void and have one int parameter.
Example: you might choose the name sigchld_handler for a signal handler for the SIGCHLD signal (termination of a child process). Then the declaration would be:

void sigchld_handler(int sig);

When a signal handler executes, the parameter passed to it is the number of the signal. A programmer can use the same signal handler function to handle several signals. In this case the handler would need to check the parameter to see which signal was sent. On the other hand, if a signal handler function only handles one signal, it isn’t necessary to bother examining the parameter since it will always be that signal number.




// CPP program to illustrate
// User-defined Signal Handler
#include<stdio.h>
#include<signal.h>
  
// Handler for SIGINT, caused by
// Ctrl-C at keyboard
void handle_sigint(int sig)
{
    printf("Caught signal %d\n", sig);
}
  
int main()
{
    signal(SIGINT, handle_sigint);
    while (1) ;
    return 0;
}


Output:

^CCaught signal 2  // when user presses ctrl-c
^CCaught signal 2 

Sending signals via kill()

We can send a signal using kill() to the process.

int kill(pid_t pid, int signal);
pid: id of destination process
signal: the type of signal to send
Return value: 0 if signal was sent successfully

Example:

pid_t iPid = getpid(); /* Process gets its id.*/
kill(iPid, SIGINT);  /* Process sends itself a  SIGINT signal   
(commits suicide?)(because of SIGINT 
signal default handler is terminate the process) */
        

Questions

1. What is the Output of the following program?




#include<stdio.h>
#include<wait.h>
#include<signal.h>
int main()
{
    int stat;
    pid_t pid;
    if ((pid = fork()) == 0)
        while(1) ;
    else
    {
        kill(pid, SIGINT);
        wait(&stat;);
        if (WIFSIGNALED(stat))
            psignal(WTERMSIG(stat), "Child term due to");
    }
}


Output:

 Child term due to: Interrupt

2. What is the Output of the following program?




#include<stdio.h>
#include<signal.h>
#include<wait.h>
int val = 10;
void handler(int sig)
{
    val += 5;
}
int main()
{
    pid_t pid;
    signal(SIGCHLD, handler);
    if ((pid = fork()) == 0)
    {
        val -= 3;
        exit(0);
    }
    waitpid(pid, NULL, 0);
    printf("val = %d\n", val);
    exit(0);
}


Output:

val = 15 

3. Consider the following code. What is the output?




#include<stdio.h>
#include<wait.h>
#include<signal.h>
pid_t pid;
int counter = 0;
void handler1(int sig)
{
    counter++;
    printf("counter = %d\n", counter);
    /* Flushes the printed string to stdout */
    fflush(stdout);
    kill(pid, SIGUSR1);
}
void handler2(int sig)
{
    counter += 3;
    printf("counter = %d\n", counter);
    exit(0);
}
  
int main()
{
    pid_t p;
    int status;
    signal(SIGUSR1, handler1);
    if ((pid = fork()) == 0)
    {
        signal(SIGUSR1, handler2);
        kill(getppid(), SIGUSR1);
        while(1) ;
    }
    if ((p = wait(&status;)) > 0)
    {
        counter += 4;
        printf("counter = %d\n", counter);
    }
}


Output

counter = 1         //(parent’s handler) 
counter = 3         //(child’s handler) 
counter = 5         //(parent’s main) 


Previous Article
Next Article

Similar Reads

Communication between two process using signals in C
Prerequisite : C signal handling In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call. fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).The parent can then send messages t
3 min read
Program error signals
Signals in computers are a way of communication between the process and the OS. When a running program undergoes some serious error then the OS sends a signal to the process and the process further may not execute. Some processes may have a signal handler that does some important tasks before the process leaves the CPU. Signal and interrupt are bas
3 min read
Control Signals in 8155 Microprocessor
In handshake mode, when both the ports A and B are configured, port A uses the lower three signals of port C(i.e, PC0, PC1, PC2) and port B uses the upper three signals (i.e, PC3, PC4, PC5). The diagram can be followed as: Figure - 8155 with Handshake mode The functions of the above signals can be seen as follows: STB (Strobe Input): This is an inp
2 min read
Difference Between C Language and LISP Language
C Language: C is the procedural Programming language. It was designed to be compiled using a compiler. The Language has small and fixed number of keywords like if/else, for, while,.. etc. We can use more than one assignment that may be used in one statement in this language. Functions are also used here, it can return values that can be ignored, wh
2 min read
fgets() and gets() in C language
For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets(). fgets() The fgets() reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character
3 min read
isxdigit() function in C Language
isxdigit() function in C programming language checks that whether the given character is hexadecimal or not. isxdigit() function is defined in ctype.h header file. Hexadecimal equivalent of Decimal Numbers: Hexadecimal: 0 1 2 3 4 5 6 7 8 9 A B C D E F Decimal: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Syntax: char isxdigit( char x); Examples: Input : A
2 min read
isupper() function in C Language
isupper() function in C programming checks whether the given character is upper case or not. isupper() function is defined in ctype.h header file. Syntax : int isupper ( int x ); Examples: Input: A Output: Entered character is uppercase character Input: a Output: Entered character is not uppercase character Input: 1 Output: Entered character is not
2 min read
isalnum() function in C Language
isalnum() function in C programming language checks whether the given character is alphanumeric or not. isalnum() function defined in ctype.h header file. Alphanumeric: A character that is either a letter or a number. Syntax: int isalnum(int x); Examples: Input : 1 Output : Entered character is alphanumeric Input : A Output : Entered character is a
2 min read
trunc() , truncf() , truncl() in C language
All three functions are used to remove digits after decimal point and return the modified decimal number. trunc() : Truncates a double value after the decimal point and gives the integer part as the result. The return value and the arguments are of the type double. Syntax : double trunc(double x); Parameters: x :It takes a double value as an input
4 min read
How to clear console in C language?
It is one of the basic need a program may required i.e clear the console during execution time. Need of a clear console screen : A console screen must be cleared once its stated objectives have been completed. A user also needs a clear screen for new data. Like any other language, C offers a variety of ways to clear the console screen. The clear sc
7 min read
three90RightbarBannerImg