Handling End Of File (eof)

In the previous example, the expect command waited for output for a specific period of time. If the program terminates, there can be no more output forthcoming. expect recognizes this. Specifically, expect recognizes the closing of the connection to the spawned process. This closing is referred to as end of file or more succinctly, eof.[20]

While it is not a rule, usually a process closes the connection just prior to exiting. By default, the expect command simply returns when it sees an eof (i.e., closing). In light of this, it is worth reviewing the maxtime script.

After the maxtime script spawned a process, expect waited. Since there were no patterns, the output could not match. If the process continued running up to the timeout period, expect would return and the script would return. If the process stopped running before the timeout period, the process would first close the connection. expect would see this as an eof. Again, expect would return and then the script would return.

Similarly to the way an action is associated with a timeout, it is possible to associate an action with an eof. The special pattern eof is used. For example, the maxtime script could use this to report whether the spawned program completed within the allotted time or ran over.

#!/usr/local/bin/expect --
set timeout [lindex $argv 0]
eval spawn [lrange $argv 1 end]
expect {
    timeout {puts "took too much time"}
    eof     {puts "finished in time"}
}

Here are some test cases called from the shell using the UNIX sleep command. The sleep command is the perfect program to test with since it waits for exactly the amount of time you request.

% maxtime 2 sleep 5
spawn sleep 5
took too much time
% maxtime 5 sleep 2
spawn sleep 2
finished in time

In the first case, sleeping for five seconds took longer than two, so the script reported that it "took too much time“. In the second case, sleeping for two seconds is easily accomplished in five seconds, so the script said "finished in time“.



[20] The terminology comes straight from UNIX, where all output sources can be viewed as files, including devices and processes.

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.