Signal capture trap tool in shell

Signal capture trap, which captures a specified signal and executes predefined commands. For example, pressing Ctrl+C will terminate the execution of the script. In fact, the system sends a SIGINT signal to the script process. The default way to process the SIGINT signal is to exit the program. If you want to not quit the program at Ctrl +C, you have to use the trap command to specify how the SIGINT will be handled. The trap command handles not only Linux signals, but also script exit (EXIT), debugging (DEBUG), error (ERR), return (RETURN), and so on.

Grammatical Explanation

trap format

It captures the specified signal and executes predefined commands.

trap [-lp] [[arg] sigspec ...]
  • arg
    Is a shell command or custom function or script

  • sigspec
    sigspec can be a signal name or a numeric value. The case of the signal name is insensitive, and the SIG prefix is optional. The following commands have the same effect

trap "echo trap int" 2
trap "echo trap int" int 
trap "echo trap int" Int
trap "echo trap int" INT 
trap "echo trap int" SIGINT

You can also write multiple semaphores at the same time

trap 'echo "Press ctrl+c"' 2 3

Signals and uses

  • Trap-l: You can see how many semaphores there are by looking at an output like kill-l through trap-l
[root@mdns zaishu]#trap -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
16) SIGSTKFLT   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
  • Introduction to Linux Signals
    For example, the common ctrl +c termination process corresponds to sigint, which is 2. ctrl+z (pause process, enter background)
1) SIGHUP This signal is connected at the user terminal(Normal or abnormal)Send at end, Usually at the end of the terminal's control process, Notify Same session Each job within, At this point they are no longer associated with the control terminal.   
2) SIGINT Program termination(interrupt)signal, Type in User INTR character(Usually Ctrl-C)When issued   
3) SIGQUIT and SIGINT Similar, But by QUIT character(Usually Ctrl-/)Control. The process is receiving SIGQUIT Exit will occur core file, Similar to a program error signal in this sense.   
4) SIGILL Illegal Directive Executed. Usually this is due to an error in the executable itself, Or try to execute a data segment. This signal may also be generated when the stack overflows.   
5) SIGTRAP Directed by a breakpoint or other trap Instruction Generation. from debugger Use.   
6) SIGABRT The program itself finds an error and calls it abort Generated when.   
7) SIGIOT stay PDP-11 Upper by iot Instruction Generation, On other machines and SIGABRT equally.   
8) SIGBUS Illegal address, Include memory address alignment(alignment)error. eg: Access a four-word integer, But its address is not a multiple of 4.   
9) SIGFPE Issued when a fatal arithmetic error occurs. Not only floating-point operation errors, All other arithmetic errors, such as overflow and division by zero, are also included..   
10) SIGKILL Used to immediately end a program. This signal cannot be blocked, Processing and Ignoring.   
11) SIGUSR1 Reserved for user use   
12) SIGSEGV Attempt to access memory not allocated to oneself, Or attempting to write data to a memory address that does not have write permission.   
13) SIGUSR2 Reserved for user use   
14) SIGPIPE Broken pipe   
15) SIGALRM Clock timer signal, Calculated is the actual time or clock time. alarm Function uses this signal.   
16) SIGTERM Program End(terminate)signal, and SIGKILL The difference is that the signal can be blocked and processed. Usually used to require the program to exit normally itself. shell command kill This signal is generated by default.   
17) SIGCHLD End of child process, The parent process receives this signal.   
18) SIGCONT Let one stop(stopped)Processes continue to execute. This signal cannot be blocked. You can use one handler To enable the program to stopped Complete specific work when status changes to continue execution. for example, Redisplay prompt   
19) SIGSTOP Stop it(stopped)Process Execution. notes l Mean it and terminate as well as interrupt Differences between: The process has not yet ended, Just suspend execution. This signal cannot be blocked, Handle or Ignore.   
20) SIGTSTP Stop the process from running, But the signal can be processed and ignored. User Type SUSP Character time(Usually Ctrl-Z)Send out this signal   
21) SIGTTIN When a background job reads data from a user terminal, All processes in the job will receive SIGTTIN signal. These processes will stop executing by default.   
22) SIGTTOU Be similar to SIGTTIN, But at the write terminal(Or modify terminal mode)Received on time.   
23) SIGURG Has emergency data or out-of-band Data arrival socket Generated when.   
24) SIGXCPU Exceed CPU Time resource constraints. This limitation can be getrlimit/setrlimit To read/change   
25) SIGXFSZ File size resource limit exceeded.   
26) SIGVTALRM Virtual Clock Signal. Be similar to SIGALRM, But the calculation is for the process occupancy CPU time.   
27) SIGPROF Be similar to SIGALRM/SIGVTALRM, But include those used by the process CPU Time and time of system call.   
28) SIGWINCH Issued when window size changes.   
29) SIGIO File Descriptor Ready, You can start typing/Output Operation.   
30) SIGPWR Power failure

Most commonly used signals

Ctrl + c: Program termination signal, or 2 or int
EXIT: The command to execute trap settings before the shell exits, or 0
RETURN: When the function returns, or. Execute commands set by trap when returned from executing other scripts with source
DEBUG: A command that executes trap settings before any command is executed, but only once for a function before the first command of the function

Common trap commands

  • trap "script or command" signal-list
    When the script receives a signal listed in the signal-list list list, the trap command executes the command in double quotes instead of the original operation

  • trap signal-list
    If no command part is specified, the signal processing is restored. For example, trap INT indicates resuming Ctrl+C exit

  • trap "" signal-list
    Ignoring signal signals can be multiple, such as trap "" INT indicating ignoring SIGINT signals and pressing Ctrl+C will not cause scripts or commands to exit.

  • trap "-" signal-list
    Operation to restore the original signal

  • trap -p
    Print out the current trap settings

  • trap "commands" EXIT
    Commands executed when the script exits

trap -l
Print out all the signals

Example

ctrl + c example

Ctrl + c: Program termination signal, or 2 or int

[root@mdns zaishu]#trap "echo trap 2" 2
[root@mdns zaishu]#ls^Ctrap 2  # Press the command specified in the ctrl +c output trap
[root@mdns zaishu]#trap -p
trap -- 'echo trap 2' SIGINT
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU

Signal Shielding and Recovery

[ root@server ~]# trap ""2 ##Signal Shielding
[ root@server ~]# trap: 2 ##Recovery signal

[root@mdns zaishu]#trap 'echo "Press ctrl+c"' int
[root@mdns zaishu]#trap "" int
[root@mdns zaishu]#trap -p
trap -- '' SIGINT
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU
[root@mdns zaishu]#ls #Even if you press ctrl +c this command will not terminate, pressing Enter will still execute
1.sh  2  3  c  dir1  dir3
[root@mdns zaishu]#trap : 2
[root@mdns zaishu]#ls ^C  #Press ctrl+c to terminate after recovery

trap -

[root@mdns zaishu]#trap "echo trap 2" 2
[root@mdns zaishu]#^Ctrap 2

[root@mdns zaishu]#trap "-" 2
[root@mdns zaishu]#trap -p  # Clear the set semaphore
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU
[root@mdns zaishu]#trap - 2
[root@mdns zaishu]#ls ^C  # Press ctrl+c to terminate the process

debug example

DEBUG: A command that executes trap settings before any command is executed, but only once for a function before the first command of the function

#!/bin/bash
hi() {
    echo "hi shuge"
}
trap "echo this is trap" DEBUG
hi
hello() {
    echo "hello shuge"
}
hello
[root@mdns zaishu]#./1.sh 
this is trap  # Execute commands in trap before function execution
hi shuge
this is trap # Execute commands in trap before function execution
hello shuge

exit example

exit

#!/bin/bash
hi() {
    echo "hi shuge"
    echo "hi shuge2"
}

hi
hello() {
    echo "hello shuge"
}
hello
trap "echo this is trap 0" 0
[root@mdns zaishu]#./1.sh 
hi shuge
hi shuge2
hello shuge
this is trap 0 #Execute the command specified in trap before the script exits

return example

return

#!/bin/bash
hi() {
    trap "echo this is trap return" return
    echo "hi shuge"
    echo "hi shuge2"
}

hi
hello() {
    trap "echo this is trap return" return
    echo "hello shuge"
}
hello
[root@mdns zaishu]#./1.sh 
hi shuge
hi shuge2
this is trap return
hello shuge
this is trap return

Comprehensive Case 1

#!/bin/bash

trap "echo 'Sorry!I have trapped Ctrl+C'" 2
echo "This is a test script~"

count=1

while [ $count -le 3 ]; do
    echo "Loop #$count"
    sleep 2
    count=$(($count + 1))
done

echo "This is the end of the script~"
trap - 2 ##recovery
echo "I just removed the trap"
[root@mdns zaishu]#./1.sh 
This is a test script~
Loop #1
Loop #2
^CSorry!I have trapped Ctrl+C
Loop #3
This is the end of the script~
I just removed the trap
#!/bin/bash
trap 'echo "Press ctrl+c"' int
trap -p
for ((i = 0; i <= 3; i++)); do
    sleep 1
    echo $i
done
trap '' int
trap -p
for ((i = 4; i <= 6; i++)); do
    sleep 1
    echo $i
done
trap '-' int
trap -p
for ((i = 7; i <= 9; i++)); do
    sleep 1
    echo $i
done

Effect:

[root@mdns zaishu]#./1.sh 
trap -- 'echo "Press ctrl+c"' SIGINT
1
^CPress ctrl+c	# Command corresponding to output signal
2
3
trap -- '' SIGINT
4
^C5	#Shielding signal
6
7
^C	#Recovery signal, terminal process

When the script is executed, delete all new files when the script is finished

#!/bin/bash

trap "find /root/zaishu -type f -name 'shu_*' | xargs rm -f && exit "  0

new_file(){
    touch /root/zaishu/shu_$(date +%F-%N-%M-%S)
    sleep 2
    touch /root/zaishu/shu_$(date +%F-%N-%M-%S)
    ls -l /root/zaishu/shu*
}

new_file
[root@mdns zaishu]#./1.sh #Two files are generated during script execution
-rw-r--r-- 1 root root 0 Feb  3 23:01 /root/zaishu/shu_2022-02-03-194183486-01-14
-rw-r--r-- 1 root root 0 Feb  3 23:01 /root/zaishu/shu_2022-02-03-205999803-01-16
[root@mdns zaishu]#ls  # Delete the new file after execution
1.sh  2  3  c  dir1  dir3

summary

Keywords: Linux bash

Added by Crys on Thu, 03 Feb 2022 20:57:17 +0200