Linux 进程管理、任务调度及脚本嵌入技术全解析
1. 信号处理与临时文件管理
在 Linux 中,有时需要在进程因接收到信号而突然退出之前执行一些特定的任务。下面的 shell 脚本展示了如何使用trap命令来实现这一功能:
#!/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在这个脚本中,当接收到SIGHUP、SIGINT、SIGABRT、SIGT