multithreadingasynchronouserror-handlingtcldev-null

How to suppress errors/outputs from a TCL thread?


I have created a thread :

set t1 [thread::create]
thread::send $t1 {
    proc myProc {command args} {
        exec {*}[auto_execok $command] {*}$args >& /dev/null
    }
}

And then tried to send an asynchronous command :

thread::send -async $t1 [list myProc <command args>]

But the error/output from the command is getting displayed in output. How to hide the errors/outputs from the command that is send to the async thread ?


Solution

  • The simplest method is to catch the errors.

    thread::send $t1 {
        proc myProc {command args} {
            catch {
                exec {*}[auto_execok $command] {*}$args >& /dev/null
            }
        }
    }
    

    Be aware that this makes any problems significantly more difficult to debug! It's better if you can identify what errors you expect and just try to catch them, so unexpected errors are still things you see and have to handle.

    thread::send $t1 {
        proc myProc {command args} {
            try {
                exec {*}[auto_execok $command] {*}$args >& /dev/null
            } trap CHILDSTATUS {} {
                # Ignore a non-zero exit?
            }
        }
    }
    

    For this specific case (which is very much I/O-bound from Tcl's perspective) you might be better off just adding & to the end of the exec call and not running in a separate thread. Can't really say for sure without knowing exactly what you're doing, but it is worth considering.