Checking For Errors From spawn
All of the examples so far have assumed that spawn always succeeds. The bad news is that spawn does not always succeed. The good news is that it only fails in peculiar environments or in peculiar situations. In this section, I will describe the meaning of “peculiar” and how to check whether spawn succeeded or not.
The spawn command normally returns the process id of the newly spawned process.[50] This is generally of little value since spawned processes are more easily manipulable by their spawn ids. However, it is occasionally useful to be able to kill a process using its process id rather than going through some long interaction.
set pid [spawn program] . . . # some time later exec kill $pid
Once killed, the process connection should be recycled by calling close and wait.
Running out of various system resources can cause spawn to fail. For example, spawn allocates dynamic memory as well as a logical terminal interface. Failures like this can be caught using Tcl’s catch command:
if [catch "spawn program" reason] {
send_user "failed to spawn program: $reason\n"
exit 1
}
Even if spawn does not return an error, that is not a guarantee that it was entirely successful. To understand why, it is necessary to explain a little of how spawn is implemented.
The spawn command follows the traditional UNIX paradigm for running a new program. First, Expect forks. Forking is the UNIX way of generating a new process. Initially, the new process is still running Expect code. ...