sid_com
sid_com

Reputation: 25117

How to exit after catching a Ctrl+C?

After I've caught a CtrlC to do a cleanup is it more correct to exit the program with kill( 'INT', $$ ) than exit the program with exit()?

Upvotes: 1

Views: 1181

Answers (1)

amon
amon

Reputation: 57640

Ctrl-C sends the INT signal to your process. Sending another INT after handling that is useless:

perl -E'$SIG{INT}=sub{say "interrupted"; $c++ < 5 and kill INT => $$}; <>'

This is an unusual way to implement recursion gotos, but no amount of ^C ^C ^C will terminate the program. (Press enter to exit).

If you want to exit the program, do just that (preferably with non-zero status).


Relevant quote from perlmod:

An END code block is executed as late as possible, that is, after perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. (But not if it's morphing into another program via exec, or being blown out of the water by a signal—you have to trap that yourself (if you can).

I.e. the self-interrupting kill INT => $$ would not execute END blocks by default. This probably stems from the “make difficult things possible” philosophy. Unless certain exit operations can take very long time to run, you should still perform them on INT or TERM signals. If users whish immediate shutdown, there still is KILL.

Upvotes: 4

Related Questions