Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Signal
3.
Sending Signals using kill command 
3.1.
Syntax
3.2.
Example 
4.
Trap Command
4.1.
Syntax
4.2.
Example
4.3.
User-defined function as Handler
5.
Ignore a signal 
5.1.
Syntax
5.2.
Example 
6.
Re-enable Signals
6.1.
Syntax
6.2.
Example
7.
Only trap command
7.1.
Syntax
8.
Frequently Asked Questions
8.1.
What is the difference between SIGKILL and SIGTERM? 
8.2.
What is the difference between SIGKILL and SIGSTOP? 
8.3.
How to view the list of all the signals?
9.
Conclusion
Last Updated: Mar 27, 2024

Signals and Traps in Shell Scripts

Author Neha Chauhan
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

During the execution of a process, when a Signal is encountered the operating system stops the normal flow of the process to deliver the signal. In case, the process has pre-defined a task to be performed when a signal is received then the Operating system will perform that task. 

Sometimes the signals disrupt the proper operation of the process, this can be prevented by trapping the signal. A trap command is used to trap the signal. The trap command will either ignore the signal or clean up waste files and stop the process. 

Signals and traps

In this article, we will discuss about signals and the trap command in detail. 

Signal

A Signal is a numeric message that is sent to running applications from the operating systems. When an operating system encounters a signal during the execution of a process, it interrupts the process and performs the action specified by the signal or action specified by the process. 

The most common signals used in Shell programming are - 

Signal Name 

Derivation

Description

Keyboard Shortcut

Signal Number

SIGINT

SIGnal INTerrupt

It terminates the process i.e. it tells the process to stop what it is doing and waits for the user's input. The process takes time to clean up after itself. 

Ctrl + C

2

SIGKILL

SIGnal KILLer

It kills the process immediately i.e. it tells the process to just stop what it is doing NOW and not wait to clean up anything. 

-

9

SIGTERM

SIGnal TERMinate

It terminates the process cleanly. The process cleans up after itself and then terminates the process. It is the default signal that is sent when we call the kill command. 

This signal often gets ignored by the processes and is a weak signal. 

-

15

SIGHUP

SIGnal Hang UP 

If a process is being run from a terminal and that terminal itself is closed/terminated then the process receives this signal and consequently terminates. The process might ignore this signal if it does not want to be interrupted.

-

1

SIGQUIT

SIGnal QUIT

It interrupts the process and creates a core dump, which can be used for debugging. A core dump is a file named ‘core’ that contains the memory image of the process. 

Ctrl+D 

3

SIGSTOP

SIGnal STOP 

It pauses the process. 

-

19

 

 

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

Sending Signals using kill command 

You can send signals by using the kill command followed by the name or number of the signal and the process ID. 

Syntax

kill -<signal_name or signal_number> <process_id>

Example 

Let’s run the following code - 

echo “process id is $$”
while true
do
    echo Test
    sleep 1
done

Yes, you are correct. It is an infinite loop. 

Output

From the above output, we can see that the PID for this process is 2975.

If you want to come out of this infinite loop, you can run the following command in a new terminal - 

$ kill -SIGINT 2975

$ kill -SIGINT 2975

You can also use ctrl+c command to send SIGINT signal.

The signal number of SIGINT is 2. The above command can also be written as -

$ kill -2 2975

NOTE: You can ignore the SIG in your commands i.e. you can write kill -SIGINT as kill -INT.

You can get a list of all the commands by running the following command - 

kill -l

Trap Command

The trap command executes a handler (a handler is a task specified by the user) when a signal is received.

Syntax

trap <handler or arguments> <signal> 

Example

trap “echo Exit command is detected” 0
echo “Hello Ninja!” 
exit 0

 

Let’s understand what is happening in this script. 

trap “echo Exit command is detected” 0

✔️ “echo Exit command is detected” is the handler that will be executed by the trap command when the signal 0 is detected.  

 

echo “Hello Ninja!” 
exit 0

✔️ This script will be executed after tracing the trap command. 

“Hello Ninja!” will be printed on the screen and a signal 0 (or exit signal) will be sent to the trace command. 

When we run the above script, the following output is produced - 

Output

We hope it clears up how the trap command works. Let’s learn some more about trap command!

User-defined function as Handler

A handler can be a valid UNIX (or BASH) command or it can be a user-defined function. 

Let’s take an example and understand how to use a User-defined function as a handler - 

echo_something(){
echo “Exit command is detected” 
}
trap echo_something 0
echo “Hello Ninja!” 
exit 0 

✔️ In the above example, we have created a function called echo_something. 

✔️ We are using the function echo_something() as the handler with the trap command. 

✔️ The handler function echo_something() will be executed when a signal 0 is received by the trap command. 

✅ The output will be as follows - 

Output

Ignore a signal 

When we are working with sensitive commands or with a sensitive project, it would be safe to ignore any signal that might interrupt the process. 

We can use the null string (“”) as the signal handler with the trap command to ignore a signal. 

Syntax

trap “” <signals> 

 

Example 

trap “” SIGINT SIGABRT

✅ When we run the above command, SIGINT and SIGABRT will be ignored when running the file. 

Re-enable Signals

After ignoring the signal using the “” as a handler, if you want to enable the signal i.e. you want the shell to stop ignoring the signals, put a - (dash) as the handler. 

Syntax

trap - <signal/s>

 

Example

trap - SIGINT SIGABRT

✅ When we run the following command, the signals SIGINT and SIGABRT will be re-enabled. 

Only trap command

If you use only trap command without any handler or a signal, it will display a list of all currently set signal traps. 

Syntax

trap 

✅ After running the trap “” SIGINT SIGABRT command, if we run trap command then we will obtain the following output - 

Output

Frequently Asked Questions

What is the difference between SIGKILL and SIGTERM? 

SIGKILL will terminate the process without doing any cleanup and hence create zombie child processes while SIGTERM will terminate the process gracefully and clean up after itself and it does not kill the child process. 

What is the difference between SIGKILL and SIGSTOP? 

SIGKILL will terminate the process and SIGSTOP will just pause the process and it will resume the process when you send a SIGCONT signal. 

How to view the list of all the signals?

You can view the list of all the signals by running the kill -l command.  

Conclusion

Pat yourself on the back👏 for finishing this article. In this article, we discussed what are signals in shell scripting and how to send signals to a process. We also discussed about the trap command in shell scripting. 

Do not stop learning! We recommend that you read these articles - 

🔥 Introduction to Linux

🔥 Linux Kernel

🔥 Linux Directories

🔥 Linux Commands list

Head to the Guided Path on the Coding Ninjas Studio and upskill in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more courses.

If you want to Practice top Coding Problems, attempt mock tests, or read interview experiences, head to the Coding Ninjas Studio, our practice platform.

We wish you Good Luck!🎈 Please upvote our blog 🏆 and help other ninjas grow.

Previous article
Comments And Variables in Shell Scripting
Next article
Shell Scripting - While Loop
Live masterclass