Example—chess Versus chess
Very useful results can be produced by communicating with multiple processes. A simple but amusing example is the problem of having one chess
process play a second chess
process. In order to accomplish this, the standard output of one process must be connected to the standard input of another, and vice versa.
Figure 10-1.
As an Expect script, the basic idea might be implemented this way:
set timeout −1 spawn chess ;# start player one set chess1 $spawn_id spawn chess ;# start player two set chess2 $spawn_id while 1 { expect "(.*)\n" ;# read move set spawn_id $chess1 send $expect_out(1,string) ;# send move to other ;# player expect "(.*)\n" ;# read response set spawn_id $chess2 send $expect_out(1,string) ;# send back }
The first four lines start two chess
processes and save the respective spawn ids. Then the script loops. The loop starts by reading a move from the first process. spawn_id
is changed to the second process, and the move is sent there. The response is collected, spawn_id
is set back to the original chess
process, and the response is sent back to the first process. The loop repeats, allowing moves to go back and forth.
Alas, the UNIX chess
program was not intended to read its own output, so the output has to be massaged a little before being used as input.[40] Oddly, the program prints out moves differently depending on if it goes first or second. ...
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.