Version 1 of signal

Updated 2002-04-05 16:02:25

How can a command-line Tcl application catch and gracefully process signals such as control-C? It can't--not without an extension. Signal handling is not part of core Tcl, as of version 8.4.

The most popular signal-aware extensions are Expect and TclX (available, incidentally, through the popular ActiveTcl distribution).


And what about signal handling from C extensions to Tcl? Say I'm writing some loadable module, and need to register an handler with SIGFPE. What TCL functions are safe to call? Which aren't?


Extended Tcl has a signal command:

   signal action siglist [command]

   where action is one of "default", "ignore", "error", "trap", "get",
   plus the POSIX "block" and "unblock" actions (available only on
   POSIX systems, of course). Siglist is a list of either the symbolic
   or numeric Unix signal (the SIG prefix is optional). Command is your
   error handler (or a simple {puts stdout "Don't press *that* key!"} :-)
   trap does what you expect, and I find error and get to be extremely
   useful in interactive programs which demand keyboard traversal.

Americus P offers this example of signal usage:

    package require Tclx 8.0
    set cntrlc_flag 1

    proc mysig {} {
            global cntrlc_flag
            puts stdout "Aborting current routine"
            set cntrlc_flag 0
    }

    signal trap SIGINT mysig

    The procedure that uses the interrupt looks like this:

    proc infinite {} {
        global cntrlc_flag
        set cntrlc_flag 1
        set a 0
        while {$cntrlc_flag == 1} {
            set a [expr $a+1]
            puts "Loop: $a"
        }
    }