Chapter 11. Handling Multiple Processes Simultaneously

In the previous chapter, I introduced the concept of a spawn id and how the spawn_id variable could be used to change the attention of Expect commands between multiple processes. In this chapter, I will demonstrate a mechanism that provides a more explicit way of denoting the current spawn id. Explicitly naming spawn ids makes it possible to handle multiple spawn ids in the same command.

I will also cover the expect_before and expect_after commands, which can greatly simplify scripts by performing common tests (such as for eof and timeout) in only a single command of the script.

Implicit Versus Explicit Spawn Ids

The previous chapter demonstrated various ways of interacting with two processes, an ftp process and a write process. By setting the variable spawn_id, the send and expect commands can communicate with either process. Here is an example of that from the previous chapter:

set spawn_id $ftp
send "get $file1\r";                            expect "220*ftp> "

set spawn_id $write
send "successfully retrieved file\r"

set spawn_id $ftp
send "get $file2\r";                            expect "220*ftp> "

It is also possible to supply send and expect with an explicit parameter representing a spawn id. In this case, the commands do not use the spawn_id variable. Instead the spawn id is passed as an argument following the flag "-i“. For example:

send -i $write "successfully retrieved file\r"

This command sends the string to the write process. The value of spawn_id is irrelevant, as send ...

Get Exploring Expect now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.