Treating Files As Spawned Processes

In UNIX, devices are files. Or at least, it is convenient to think that they are. Devices appear in the file system, and file-like operations can be performed on them. Expect uses these beliefs to support operations like expect and send.

In fact, these can be applied to files as well. In the previous chapter, I described how you can make any file look like a spawned process—for example, by spawning a process to read it with cat. A more direct way is possible.

Tcl’s open command is capable of opening files. The open command returns a file identifier which can be used as an argument to gets, puts, etc. Using the -open argument of spawn, the file id can be turned into a spawn id.

set file [open "/etc/passwd" r]
spawn -open $file
expect . . .

This example opens the /etc/passwd file and searches through it until the given pattern appears. After the spawn, the file behaves exactly like a process. While there is no real process, for consistency, the file must be waited for after being closed. The value returned by wait always indicates a normal exit and can be ignored. This allows you to write code in which it does not matter whether a real process was spawned or not.

The first two commands in the fragment above can be condensed to one:

spawn -open [open "/etc/passwd" r]

Once the file has been passed to spawn, it should not be accessed by gets, puts, or any other Tcl function. Expect and Tcl do not share buffers internally, so joint access should generally ...

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.