2019-04-19 07:03:37 -04:00
|
|
|
// +build !windows
|
|
|
|
|
|
|
|
package pty
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 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.
|
2020-11-03 07:44:13 -05:00
|
|
|
//
|
|
|
|
// Starts the process in a new session and sets the controlling terminal.
|
2019-04-19 07:03:37 -04:00
|
|
|
func Start(c *exec.Cmd) (pty *os.File, err error) {
|
|
|
|
return StartWithSize(c, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// StartWithSize 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.
|
|
|
|
//
|
2020-11-03 07:44:13 -05:00
|
|
|
// This will resize the pty to the specified size before starting the command.
|
|
|
|
// Starts the process in a new session and sets the controlling terminal.
|
2019-04-19 07:03:37 -04:00
|
|
|
func StartWithSize(c *exec.Cmd, sz *Winsize) (pty *os.File, err error) {
|
2020-11-03 07:44:13 -05:00
|
|
|
if c.SysProcAttr == nil {
|
|
|
|
c.SysProcAttr = &syscall.SysProcAttr{}
|
|
|
|
}
|
|
|
|
c.SysProcAttr.Setsid = true
|
|
|
|
c.SysProcAttr.Setctty = true
|
|
|
|
return StartWithAttrs(c, sz, c.SysProcAttr)
|
|
|
|
}
|
|
|
|
|
|
|
|
// StartWithAttrs 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.
|
|
|
|
//
|
|
|
|
// This will resize the pty to the specified size before starting the command if a size is provided.
|
|
|
|
// The `attrs` parameter overrides the one set in c.SysProcAttr.
|
|
|
|
//
|
|
|
|
// This should generally not be needed. Used in some edge cases where it is needed to create a pty
|
|
|
|
// without a controlling terminal.
|
|
|
|
func StartWithAttrs(c *exec.Cmd, sz *Winsize, attrs *syscall.SysProcAttr) (pty *os.File, err error) {
|
2019-04-19 07:03:37 -04:00
|
|
|
pty, tty, err := Open()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer tty.Close()
|
2020-11-03 07:44:13 -05:00
|
|
|
|
2019-04-19 07:03:37 -04:00
|
|
|
if sz != nil {
|
2020-11-03 07:44:13 -05:00
|
|
|
if err := Setsize(pty, sz); err != nil {
|
2019-04-19 07:03:37 -04:00
|
|
|
pty.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if c.Stdout == nil {
|
|
|
|
c.Stdout = tty
|
|
|
|
}
|
|
|
|
if c.Stderr == nil {
|
|
|
|
c.Stderr = tty
|
|
|
|
}
|
|
|
|
if c.Stdin == nil {
|
|
|
|
c.Stdin = tty
|
|
|
|
}
|
2020-11-03 07:44:13 -05:00
|
|
|
|
|
|
|
c.SysProcAttr = attrs
|
|
|
|
|
|
|
|
if err := c.Start(); err != nil {
|
|
|
|
_ = pty.Close()
|
2019-04-19 07:03:37 -04:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return pty, err
|
|
|
|
}
|