Skip to content

docs: Wait() may deadlock if child buffer is not consumed #25

@lucab

Description

@lucab

As per subject, Wait() may run into a subtle deadlock if the child buffer is not drained. Consider the following example:

package main

import "github.com/ThomasRooney/gexpect"
import "fmt"

func main() {
        fmt.Printf("Starting...\n")
        child, err := gexpect.Spawn("bash")
        if err != nil {
                panic(err)
        }
        child.Expect("$")
        fmt.Printf("Got prompt..\n")

        len := 8000
        child.SendLine(fmt.Sprintf("for i in `seq %d`; do echo 'a'; done", len))
        child.SendLine(`exit`)

        fmt.Printf("Waiting for exit...\n")
        child.Wait()

        fmt.Printf("Done\n")
        child.Close()
}

When running this, Wait() will never return. Lowering the len value, it will correctly return.

The problem with the example is that child output should be asynchronously drained while waiting, otherwise it can block when writing to the pty and deadlock with the parent (gexpect) as shown in strace:

$ strace -f -p ${BASH_PID}
write(1, "a\n", 2
$ strace -f -p ${GOEXPECT_PID}
waitid(P_PID, ${BASH_PID},  <unfinished ...>

This seems to be an intrinsic limitation of Wait(), and should be properly documented similarly to https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.wait

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions