diff --git a/README.md b/README.md index f9e5dfa..dc9e7c3 100644 --- a/README.md +++ b/README.md @@ -7,37 +7,35 @@ for other systems!) ## Install - goinstall github.com/kr/pty + go get github.com/kr/pty ## Example - package main +```go +package main - import ( - "fmt" - "github.com/kr/pty" - "io" - "os" - ) +import ( + "fmt" + "github.com/kr/pty" + "io" + "os" + "os/exec" +) +func main() { + c := exec.Command("grep", "--color=auto", "bar") + f, err := pty.Start(c) + if err != nil { + panic(err) + } - func main() { - c, err := pty.Run( - "/bin/grep", - []string{"grep", "--color=auto", "bar"}, - nil, - "", - ) - if err != nil { - panic(err) - } - - go func() { - fmt.Fprintln(c.Stdin, "foo") - fmt.Fprintln(c.Stdin, "bar") - fmt.Fprintln(c.Stdin, "baz") - c.Stdin.Close() - }() - io.Copy(os.Stdout, c.Stdout) - c.Wait(0) - } + go func() { + fmt.Fprintln(f, "foo") + fmt.Fprintln(f, "bar") + fmt.Fprintln(f, "baz") + f.Close() + }() + io.Copy(os.Stdout, f) + c.Wait() +} +``` diff --git a/run.go b/run.go index 68d1212..f0ee0e1 100644 --- a/run.go +++ b/run.go @@ -5,29 +5,22 @@ import ( "os/exec" ) -// Run starts a process with its stdin, stdout, and stderr -// connected to a pseudo-terminal tty; -// Stdin and Stdout of the returned exec.Cmd -// are the corresponding pty (Stderr is always nil). -// Arguments name, argv, envv, and dir are passed -// to os.StartProcess unchanged. -func Run(name string, argv, envv []string, dir string) (c *exec.Cmd, err error) { - c = new(exec.Cmd) - var fd [3]*os.File - var f *os.File - f, fd[0], err = Open() +// Start assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout, +// and c.Stderr, calls c.Start, and returns the File of the tty's +// corresponding pty. +func Start(c *exec.Cmd) (pty *os.File, err error) { + pty, tty, err := Open() if err != nil { return nil, err } - fd[1] = fd[0] - fd[2] = fd[0] - c.Stdout = f - c.Stdin = f - c.Process, err = os.StartProcess(name, argv, &os.ProcAttr{Env: envv, Dir: dir, Files: fd[:]}) - fd[0].Close() + defer tty.Close() + c.Stdout = tty + c.Stdin = tty + c.Stderr = tty + err = c.Start() if err != nil { - f.Close() + pty.Close() return nil, err } - return c, nil + return pty, err }