Symbolic Spawn Ids

For efficiency, Expect uses integers to represent spawn ids. For instance, if you examine the value of spawn_id, you will find it is an integer. However, you should avoid relying on this knowledge—it could change in the future.

One thing you can rely on is that a spawn id can be used as an array index. You can use this fact to associate information with the spawn ids. For example, if you have spawned several telnet sessions, you can retrieve the original hostname if you save it immediately after the spawn.

spawn telnet potpie
set hostname($spawn_id) potpie

Once saved, the hostname can be retrieved just from the raw spawn id alone. This technique can be used inside a procedure. With only the spawn id passed as an argument, the hostname is available to the procedure.

proc wrapup {who} {
    global hostname
    set spawn_id $who
    send "exit\r"
    puts "sent exit command to $hostname($spawn_id)"
}

Similar associations can be made in the reverse direction. It is also possible to associate several pieces of information with a spawn id. Consider these assignments.

spawn $cmdname $cmdarg
set proc($spawn_id,cmdname) $cmdname
set proc($spawn_id,cmdarg) $cmdarg
set proc($cmdname,spawn_id) $spawn_id

These assignments could be wrapped up in a procedure so that they occur every time you spawn a 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.