Traps

When a process is running and in between we kill the process, the process terminates instantly without doing anything further. A programmer who writes a program may want to do some tasks before a program actually terminates; for example, a clean up of the temporary directories created, saving applications' state, saving logs, and so on. In such a case, a programmer would like to listen to signals and do the required task before actually allowing you to terminate the process.

Consider the following shell script example:

#!/bin/bash
# Filename: my_app.sh
# Description: Reverse a file

echo "Enter file to be reversed"
read filename

tmpfile="/tmp/tmpfile.txt"
# tac command is used to print a file in reverse order
tac $filename > $tmpfile
cp $tmpfile $filename
rm $tmpfile

This program takes an input from a user file and then reverses the file content. This script creates a temporary file to keep the reversed content of the file and later copies it to the original file. At the end, it deletes the temporary file.

When we execute this script, it may be waiting for a user to input a text filename or maybe in between reversing the file (a large file takes more time to reverse the content). During this, if processes are terminated, then the temporary file may not get deleted. It is the programmer's task to make sure that temporary files are deleted.

To solve such a problem, we can handle the signal, perform the necessary tasks, and then terminate the process. This can be achieved by using the trap command. This command allows you to execute a command when a signal is received by a script.

The syntax of using trap is as follows:

$ trap action signals

Here, we can provide trap action to be performed. An action can be an executing command (s).

In the preceding syntax of trap, signals refers to providing one or more signal names for which an action has to be performed.

The following shell script demonstrates how trap is used to perform tasks before a process suddenly exits on receiving a signal:

#!/bin/bash
# Filename: my_app_with_trap.sh
# Description: Reverse a file and perform action on receiving signals

echo "Enter file to be reversed"
read filename

tmpfile="/tmp/tmpfile.txt"
# Delete temporary file on receiving any of signals
# SIGHUP SIGINT SIGABRT SIGTERM SIGQUIT and then exit from script
trap "rm $tmpfile; exit" SIGHUP SIGINT SIGABRT SIGTERM SIGQUIT
# tac command is used to print a file in reverse order
tac $filename > $tmpfile
cp $tmpfile $filename
rm $tmpfile

In this modified script, when any of the signals such as SIGHUP, SIGINT, SIGABRT, SIGTERM, or SIGQUIT are received, then rm $tmpfile; exit will be executed. This means that a temporary file will first be deleted and then you can exit from the script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.82