Search code examples
tcl

timeout using TCL


Is there a way in TCL to enclose a piece of code in a timeout block? What I mean by that is that the block will exit after a particular timeout even if the execution is not complete. For instance:-

timeout (interval) {
#wait for socket connection here

}

If no connection is established in interval time, the block exits.

Thanks and Regards, Anjali


Solution

  • Anjali, You are looking for vwait.

    Here is an example: Wait five seconds for a connection to a server socket, otherwise close the socket and continue running the script:

    # Initialise the state
    after 5000 set state timeout
    set server [socket -server accept 12345]
    proc accept {args} {
       global state connectionInfo
       set state accepted
       set connectionInfo $args
    }
    
    # Wait for something to happen
    vwait state
    
    # Clean up events that could have happened
    close $server
    after cancel set state timeout
    
    # Do something based on how the vwait finished...
    switch $state {
       timeout {
          puts "no connection on port 12345"
       }
       accepted {
          puts "connection: $connectionInfo"
          puts [lindex $connectionInfo 0] "Hello there!"
       }
    }
    

    Edit You will need to communicate with your UART device using non blocking I/O.