We now run our code, in this case just a for loop to simulate a long-running process, within a go-routine alongside the signal capturing code and block the execution of
main
with
err = <-errs
. When an error is triggered main will return, running all deferred functions first. If we run the
program and press
CTRL+C
during execution the output is
in the for loop, iteration 0
in the for loop, iteration 1
in the for loop, iteration 2
in the for loop, iteration 3
in the for loop, iteration 4
in the for loop, iteration 5
in the for loop, iteration 6
^Cexiting with error: signal trapped: interrupt
The last line indicates that our deferred function has run successfully.