I have a script
You can use the
trap to catch a signal (except
STOP) and do the required cleanup.
For example, here i am catching the pseudo signal
EXIT that would cover any signal that would make the shell to exit:
xterm -e '/bin/bash' -c 'trap "echo ok >/tmp/foobar" EXIT; sleep 5'
sleep 5 is my main task and
echo ok >/tmp/foobar is cleanup task upon exiting.
Alternately if are sure about the signal to be sent/received e.g.
INT, you can trap those directly.