简体   繁体   中英

Catching Ctrl-C of a script within a script

I want to write a kind of macro script. In this script I am calling a bash script which I have no access to which has to be killed with ctrl-c. I now want to do some clean up in my script after the called script has terminated.

How can I catch the ctrl-c of the nested script?

Edit: This is how I catch ctrl-c in a non-nested script

# trap ctrl-c and call ctrl_c()
trap ctrl_c INT
function ctrl_c() {
    echo "** Trapped CTRL-C"
}

Terminology: I'm using PARENT for the parent script, CHILD for the child script.

If you do not have access to (I'm assuming, you can not change) the CHILD script, you will not be able to catch a signal on it's behalf, even as it's parent.

However, since the PARENT process can check the exit status of the CHILD, you can detect exit by INT signal, assuming the CHILD uses the default processing of CTRL/C.

In Parent:

# Needed to prevent the parent from aborting on INT
trap 'echo "Got Signal"' INT
run-child-command ; X=$?
if [ "$(kill -l $X)" = INT ] ; then
   echo "Child killed with INT"
   echo "Cleanup ..."
   ...
fi
# Restore origianl INT signal, if needed
trap - int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM