Updated 2018-05-03 07:11:59 by dbohdan

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.6.

The most popular signal-aware extensions are Expect and TclX (available, incidentally, through the popular ActiveTcl distribution). TWAPI also has signal handling support [1] for Windows.

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?

TclX  edit

TclX has a signal command:
signal ?-restart? 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"
    }
}

TV Remember that on various systems, signals can get lost, and repeated signals masked and the order of signal reception not guaranteed. Sending a message over a socket (or pipe) is preferable over using signals, usually, except of course probably when using 'kill' or 'sleep' signals.

On windows, cygwin gives you signals but than behaviour could be even more unpredictable, though it is possible to use signals unix-like. - RS confirms that the above sample code for SIGINT runs as expected on Windows XP, with or without Cygwin.

tclsignal  edit

What signal
Where https://web.archive.org/web/20170719020829/schwartzcomputer.com/tcl-tk/tcl-tk.html (v1.5, updated 2015-03-21)
https://github.com/wjoye/tclsignal (fork of v1.4, updated 2017-08-14)
Description Unix/POSIX Signal handling for Tcl. This extension adds dynamically loadable signal handling to Tcl/Tk scripts.
Author [Michael Schwarz]