work with new os/exec

This commit is contained in:
Keith Rarick
2012-02-01 21:46:36 -08:00
parent 3b1c6581cb
commit 59dd1489cc
2 changed files with 38 additions and 47 deletions

View File

@@ -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()
}
```

31
run.go
View File

@@ -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
}