Question: I have a bash script process which at some point executes a long-running subprocess synchronously.
During the run of that subprocess, a signal is sent directly to the bash script process requesting the script to terminate.
Is there any way to intercept that signal, terminate the subprocess and then exit the bash process?

Apparently, bash's signal handling never interrupts synchronous calls?

I cannot control the fact that the termination signal is sent to the bash process. Although if the signal could propagate to the child process, that would also solve my issue.

thanks in advance,
Broes

Answer: 
See the man page of bash, chapter **SIGNALS**:

If bash is waiting for a command to complete and receives a signal for which a trap has been set, **the trap will not be executed until the command completes**. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.

So, run your external program asynchronously and use wait. Kill it using $!.
Yes, the signal can be intercepted with 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 :                 # This is the same as "while true".
    do
        if [ $flag -ne 0 ] ; then
            kill $wrappid
            break
        fi
        sleep 1        # This script is not really doing anything.
done
echo 'end'

```

What `trap` basically does is that it executes the command between "". So here the main function is in the while loop below. In every iteration the script checks if the flag is set, if not, it sleeps for a second. Before that, we remembered the pid of the child process via `$!`. The trap issues the command when the `SIGINT` or `SIGTERM` is caught (for other signals see `kill` manual). 

The wrapper function does the same, as the main function. Additionally it calls the actual `subprocess` function (in this case subprocess is `xeyes`). When the wrapper function receives `SIGTERM` signal from the main function (main function also caught one of the signals), the wrapper function can clean up things before actually killing the subprocess. After that it breaks from the while loop and exits the wrapper function. Then the main function also breaks and prints `'end'`.

edit:
Hope I understand this correctly, you are forced to execute `xeyes &`. Then the steps would be as follows (in terminal):

```
xeyes &
subpid=$!
trap "kill $subpid && exit " SIGINT SIGTERM
.... other stuff
.... more stuff
^C #TERMINATE - this firstly kills xeyes and then exits the terminal

```