Detecting End-Of-File

Normally, a spawned process generates an eof when it exits. This can be detected by using the special pattern eof. When an eof occurs, the following action is executed. The syntax is identical to expect. For example, the following command prints out a message when an eof occurs. The return causes interact to return to its caller.

interact eof {
    puts "detected end-of-file"
    return
}

If an eof occurs but no eof pattern is given, the return action is executed by default. So you could write the fragment above more simply as just:

interact
puts "detected end-of-file"

You usually want to end an action for the eof pattern with return. It rarely makes sense to continue the interaction if the spawned process has exited. However, the next chapter has examples where it is meaningful to continue the interaction.

When interact detects an eof, it automatically closes the connection to the spawned process so that there is no need to call close explicitly. This is identical to the behavior of expect when it detects an eof. One tiny difference between expect and interact is that interact can never detect an eof from the user. Because interact puts the terminal into raw mode, the user has no way of generating an end-of-file. In expect, a ^D closes the input, but in interact a ^D is just sent on to the spawned process.

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.