Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Linux Signals
2.1.
Types of Signals
2.1.1.
Maskable
2.1.2.
Non-Maskable
3.
Signals List
4.
Default Actions
4.1.
Sending Signal
4.2.
Trapping Signal
4.3.
Null Signal
4.4.
Ignoring Signals
5.
Trap
5.1.
Resetting traps
6.
Frequently Asked Questions
6.1.
Linux has how many signals?
6.2.
What are signal processing's two primary purposes?
6.3.
What is the trap's purpose in bash?
6.4.
Which signal captures the trap?
6.5.
What signals are impossible to catch?
7.
Conclusion 
Last Updated: Mar 27, 2024
Easy

Linux - Signals and Traps

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The Linux computer system has a variety of processes in various phases. The operating system or the user application is responsible for each process. The kernel and these processes must have a mechanism to coordinate their operations. One way to do this is to use the process to alert others if something important happens. 

Linux signals and traps

Let's now discuss Linux signals and their types.

Linux Signals

A signal is a number that can be transferred between processes in asynchronous communication or from the operating system to a process in response to the pressing of particular keys or the occurrence of unusual events.

In Linux signals and traps, Signals are interrupts sent to a computer program to inform it that a critical event has occurred. These consist of user requests regarding issues with unauthorized memory access.

Linux signals

Linux uses signals to communicate between processes or between the kernel and a process. It facilitates communication between various system daemons (background process) or programs.

The signal essentially denotes a one-way notice. The kernel issued the signal to the process, another process, a different process, or the kernel itself.

Real-time signals were introduced in subsequent iterations of Linus. Signal interprocess communication is simple and lightweight, making it suitable for embedded systems.

Types of Signals

Maskable and Non-Maskable signals are the two types.

Maskable

Signals that can be altered or disregarded by the user include those like Ctrl + C. 

Non-Maskable

Non-Maskable signals are those that users cannot alter or ignore. Non-Maskable signals mostly happen when a user is warned of irreparable hardware faults.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Signals List

There is a simple method for compiling a list of all the signals which your system supports. You can use the command given below to see all the allowed signals:

kill -l 
list of all signals

The following table lists out standard signals you might encounter in Linux signals and traps.

Signal Name Description
SIGHUP Controlling terminal hang-up or controlling process death detected. "Hang up" is abbreviated as HUP. Find the terminal that has to be managed or hung up on after the control operation ends. This signal is received when a process runs from a terminal, and the terminal suddenly shuts off.
SIGQUIT When a user presses the quit signal (Ctrl + D). The program is terminated when a user delivers the SIGQUIT signal (Ctrl + D).
SIGALRM This involves invoking the alarm() function so that the process can ultimately ask the operating system for a "wake-up call" in the future. The wake-up calls will carry this signal when that time comes. It serves as a timer.
SIGABRT The software calls a function called abort(). It is an urgent halt.
SIGINT To halt a program, you send a signal interrupt or SIGINT. Using the SIGINT signal, the CTRL-C keyboard shortcut will halt a program.
SIGFPE The program encountered a floating-point exception called SIGFPE.

SIGTRAP

 

Program tracers and debuggers typically utilize the SIGTRAP.

SIGBUS

 

An attempt to access memory erroneously is called SIGBUS. It can result in alignment issues during memory access.

 

SIGSEGV Segmentation faults happen when a program tries to access memory that it isn't authorized to access, such as when writing to memory that can only be read.

SIGKILL

 

The command SIGKILL instructs the process to end instantly. This communication cannot be intercepted or disregarded. Typically, sending out SIGTERM instead of SIGKILL is preferable.
SIGPIPE When a process produces output that is given to another process through a pipe ( "{producer | consumer") and that process subsequently terminates, the SIGPIPE signal is utilized, and this signal is then transmitted to the producer.
SIGCHLD This process initially used the fork() system call to start one or more child processes.
SIGPROF After some real-time has elapsed, SIGALRM is sent, and SIGPROG is sent after the process has run for some time and the system code has been executed on its behalf.
SIGFPE It is issued if a mathematical operation that is not allowed is attempted
SIGSTOP The operating system terminates the process if a SIGSTOP signal is provided. The entire thing is in a situation where it may be restarted (by SIGCONT), but only after it receives another CPU cycle.

SIGTERM

 

A kill sends software-termination signals by default. The procedure should end as a result of this signal.
SIGWINCH The process uses the SIGWINCH signal whenever one of its windows is using the process.

SIGILL

 

It's a forbidden instruction. The software includes some machine code that the CPU cannot comprehend.

SIGPROF

 

After some real-time has elapsed, SIGALRM is sent, and SIGPROG is sent after the process has run for some time and the system code has been executed on its behalf.
SIGPWR This signal, given to the processes by a power management service, indicated that power had been switched to an emergency power supply for a brief period.
SIGTOU

Whenever an unattended process tries to print something on its terminal. The operating system sends the SIGTOU signal. The SIGTTIN is the foundation of the usual response.

 

SIGXFSZ The operating system sends a SIGXFSZ signal if a process attempts to create a file with a higher file format. Using the shell command "ulimit -t unlimited," we can also remove the file size limit, although it's more probable that anything went wrong if we did so before the run.
SIGIO Another name for SIGIO is SIGPOLL. When some input process or an output channel has consented to write, a process that can arrange for sending this signal is prepared to do so.

SIGTTIN

 

If a background process tries reading from the terminal, the SIGTTIN signal is sent to it. That signal's default response is to cause the application to terminate.
SIGURG The operating system sends the SIGURG signal whenever "urgent" out-of-band data is sent via the network connection.

Default Actions

There is a default response for each signal in Linux signals and traps. The action that a script or program executes in response to a signal is known as the default action for a signal.

Several of the potential default behaviors include the following -

  • Stopping the procedure.
  • Disregard the signal.
  • Remove the core: By doing this, a core file contains the process's memory image when the signal is received.
  • Stop the process.
  • Carry on a halted procedure.

Sending Signal

One of the most popular ways for a user to interrupt a script by pressing Cmd+C/Ctrl+C.

When you press the Cmd+C/Ctrl+C key, a SIGINT will be given to the script, and the script terminates as per the default acion.

The kill command is another typical mechanism for sending signals.

$ signal pid kill

Trapping Signal

Signals can be easily trapped. The shell program often ends immediately, and the command prompt reappears when we press Ctrl + C or the broken key on the terminal while it is running. It might only sometimes be a good idea. We may, for instance, continue to use a set of temporary files that won't be deleted. 

A trap is primarily used in one of two ways in shell scripts in Linux signals and traps:

  • Get rid of temporary files.
  • Reject the signal.

Null Signal

Investigating the process's existence is a fascinating use case for sending signals in Linux signals and traps. No signal is delivered when the kill() method is invoked with the signal parameter set to 0, which is a null signal. Instead, error checking is used to determine if the process may signal the process. This implies that we can use this approach to detect the existence of the process. Any of the following outcomes can happen when a null signal is sent:

  1. If the ESRCH error occurs, the target process does not shut down.
  2. The target process must be present and accessible for the caller to deliver a signal to the target if the call is successful.
  3. The target process is present if the EPERM error occurs, but we need more authorization to transmit the signal to the process.

Ignoring Signals

The command trap, followed by two empty quotes, can be used as a command to tell the shell to ignore specific signals. 

Any of the following commands will display the shell process that will disregard those signals:

$ trap " " 2 3
$ trap "" INT QUIT

Each signal can be denoted using either signal short or their signal id so that they can be ignored by the shell. 

Trap

When the shell receives signals or under other unique circumstances, the trap specifies and activates handlers to run in Linux signals and traps. The shell will execute the specified and activated handlers when the trap specifies or activates signals or under other unusual conditions.

The shell must read and execute the command ARG when it gets the signal(s) SIGNAL SPEC. Each signal specified is reset to its initial value if ARG is empty (and only one SIGNAL SPEC is provided) or ARG is a dash ("-"). The shell ignores each SIGNAL SPEC and the instructions it executes if ARG is the null string.

Incase the SIGNAL SPEC is EXIT (0), ARG is run when the shell exits. ARG is run before every basic command if a SIGNAL SPEC is DEBUG. Whenever a shell function or a script runs using the built-in commands "." or the source completes running, ARG is performed if a SIGNAL SPEC is a RETURN. When the -e option is enabled, a SIGNAL SPEC of ERR implies that every time a command fails and the shell would otherwise exit, ARG will be executed.

Example

Trap trap 1 7 2 3
cleanup()
{
  echo "trap alert"
  rm -rf /tmp/temp_*.$$
  echo "completed"
  exit 1
}
for i in all
do
  sed s/FOO/BAR/g $i > /tmp/temp_${i}.$$ && mv /tmp/temp_${i}.$$ $i
done

Resetting traps

If you use the trap and remove the first parameter after changing the default action to be executed in response to a signal, you can modify it back. 

For example

$ trap 4 8

By doing this, the default behavior for what should happen when signals 4 or 8 are received is restored.

Frequently Asked Questions

Linux has how many signals?

There are 31standard signalsin total, which are numbered from Numbered 1 - 31. Every signal has the letters "SIG" and a suffix indicating the type of signal . The Linux kernel has 33 distinct real-time signals supported as of version 2.2.

What are signal processing's two primary purposes?

The two main functions of the signal processing hardware are compressing sensed data and identifying significant patterns in recorded data.

What is the trap's purpose in bash?

If the script terminates due to an interruption, the trap command is typically used to clear away temporary files.

Which signal captures the trap?

Use the trap command to capture the SIGINT signal is a typical case.

What signals are impossible to catch?

SIGKILL and SIGSTOP are two signals that cannot be catched.

Conclusion 

In this blog, we have discussed Linux signals and traps with a brief description of their various types. Further we also discussed the process of sending, trapping and resetting signals.

If you think this blog has helped you enhance your knowledge of the above question, and if you want to learn more, check out our articles. Visit our website to read more such blogs. 

  1. Introduction to Linux
  2. Linux Kernel
  3. Linux Operating System

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles. Enroll in our courses and refer to the mock test and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

However, consider our paid courses to give your career an edge over others!

Happy Coding!

Live masterclass