Proper Error handling EXPECT / TCL

751 Views Asked by At

What is the best way to prevent sending commands to a dead process?

Sometimes my session gets terminated when it's supposed to be open so I end up sending commands and getting the error:

send: spawn id exp4 not open

I was trying to do something like

if [catch send "test\r"] {
      puts "send error!"
}

but it seems like the query is true every pass.

that's the simplest example, but I have more complex "send / expects" where I use capture groups etc, so putting a catch around every "send / expect" or creating a function doesn't seem that useful.

can you wrap a catch around the entire program? What is the proper way to catch errors like these?

1

There are 1 best solutions below

0
On BEST ANSWER

There's a FAQ written by the Expect author that addresses this: http://expect.sourceforge.net/FAQ.html#q64

Seems like you want something like

expect_before {
    eof { respawning_the_process }
}

I'm sure there's some wrinkles to be ironed out (like what to do when the process is supposed to end)

The problem with this:

if [catch send "test\r"] {

is two-fold:

  1. you did not put braces around the condition, so it's not getting evaluated at the right time.
  2. you did not provide the right arguments to the catch command

You would want to write:

if {[catch {send "test\r"} output] != 0} {

This can be abstracted into a proc

proc send {args} {
    set status [catch [list exp_send {*}$args] output]
    # error handling if $status is non-zero
}

"exp_send" is a builtin alias for the expect "send" command, so it's safe to override "send" with a proc, minimizing the amount of code changes you need.