How to trap exit (ctrl+c) signal in Makefile?

Viewed 3771

I'm trying to trap exit (ctrl+c) signal to perform some cleanup activity .

In shell script i followed bellow function to trap,

#To trap ctrl-c signals
trap ctrl_c INT

#To trap exit signals
trap on_exit EXIT

function ctrl_c() {
    echo "exited by user"
    exit
}

function on_exit() {
    echo "exited by user"
    exit
}

How do I achieve same in Makefile ?

2 Answers

It is possible to invoke a bash interpreter explicitly and define a trap there:

test.out:
    bash -c "trap 'rm test.tmp' EXIT; \
             echo x>test.tmp; \
             cp test.tmp test.out"

You can't trap signals in make. Try using .INTERMEDIATE for cleanup and read 5.6 Interrupting or Killing make

all: test.out

test.out: test.tmp
    sleep 10

test.tmp:
    echo x>test.tmp

.PHONY: all

.INTERMEDIATE: test.tmp

Make catches the interrupt signal and removes such files if they're part of the graph and didn't exist before launching:

$ make
echo x>test.tmp
sleep 10
make: *** [Makefile:4: test.out] Interrupt
make: *** Deleting intermediate file 'test.tmp'

If you really-really need to execute some program when make exits, spawn a background process in an initialization of some variable and let it wait for the main make process to terminate:

DUMMY := $(info launching the moniror process...)$(shell some-command& )
Related