Yes, the signal can be intercepted by the trap command. See the example below:
#!/bin/bash function wrap { local flag=0 trap "flag=1" SIGINT SIGTERM xeyes & subppid=$! while : do if [ $flag -ne 0 ] ; then kill $subppid break fi sleep 1 done } flag=0 trap "flag=1" SIGINT SIGTERM wrap & wrappid=$! while :
What trap basically consists in is that it executes a command between "". So, the main function is in the while loop below. At each iteration, the script checks to see if the flag is set; if not, it sleeps for a second. Before that, we remembered the pid of the child process through $! . The trap issues a command when capturing SIGINT or SIGTERM (for other signals, see the kill manual).
The wrapper function does the same as the main function. In addition, it calls the actual subprocess function (in this case, the xeyes subprocess). When the wrapper function receives the SIGTERM signal from the main function (the main function also falls into one of the signals), the wrapper function can clear things up before the subprocess is actually destroyed. After that, it breaks out of the while loop and exits the wrapper function. Then the main function also breaks and prints 'end' .
edit: I hope I understand that correctly, you are forced to execute xeyes & . Then the steps will be as follows (in the terminal):
xeyes & subpid=$! trap "kill $subpid && exit " SIGINT SIGTERM .... other stuff .... more stuff ^C
source share