Shell Script get CTRL+Z with Trap

社会主义新天地 提交于 2019-11-29 22:31:44

问题


I am trying to get the SIGSTOP CTRL+Z signal in my script's trap.

When my script is executing, if I temporarily suspend from execution, send a SIGSTOP signalCTRL+Z, it needs to remove the files I create in it and to kill the execution.

I don't understand why the following script doesn't work. But, more important, what is the correct way to do it?

#!/bin/bash

DIR="temp_folder"
trap "rm -r $DIR; kill -SIGINT $$" SIGSTP

if [ -d $DIR ]
then
    rm -r $DIR
else
    mkdir $DIR
fi
sleep 5

EDIT:

SIGSTOP cannot be trapped, however SIGTSTP can be trapped, and from what I understood after searching on the internet and the answer below it's the correct to trap when sending signal with CTRL+Z. However, when I press CTRL+Z while running the script it will get stuck, meaning that the script will be endlessly execute no matter what signals I send afterwards.


回答1:


There are two signals you can't trap*, SIGKILL and SIGSTOP. Use another signal.

*: without modifying the kernel

IEEE standard:

Setting a trap for SIGKILL or SIGSTOP produces undefined results.




回答2:


The problem here is you are trying to suspend a process that is already sleeping.

It is also good practice to use DIR=$(mktemp -d) in shell scripts to create temp directories.

CTRL-C is signal (2) / CTRL-Z (20):

catch_exits() {
        printf "\n$(basename $0): exiting\n" 1>&2
        rm -rf $DIR
        exit 1
}

trap catch_exits 1 2 3 15 20

DIR="$(mktemp -d)"
read -p "not sleeping" test

if you send a function to the background (such as for a cursor spinner) - then you need to disable CTRL-Z while the long process is running with:

trap "" SIGTSTP


来源:https://stackoverflow.com/questions/20182454/shell-script-get-ctrlz-with-trap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!