2022-03-28 20:23:47 +00:00
|
|
|
//go:build !aix && !solaris && !windows
|
2020-05-24 17:32:19 +00:00
|
|
|
// +build !aix,!solaris,!windows
|
2018-01-17 22:02:47 +00:00
|
|
|
|
2023-10-01 08:24:33 +00:00
|
|
|
package util
|
2018-01-17 22:02:47 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"os/signal"
|
|
|
|
|
2018-01-26 18:21:14 +00:00
|
|
|
"github.com/restic/restic/internal/debug"
|
2018-01-17 22:02:47 +00:00
|
|
|
"github.com/restic/restic/internal/errors"
|
2023-05-25 15:31:51 +00:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2018-01-17 22:02:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func tcsetpgrp(fd int, pid int) error {
|
2023-05-25 15:31:51 +00:00
|
|
|
// IoctlSetPointerInt silently casts to int32 internally,
|
|
|
|
// so this assumes pid fits in 31 bits.
|
|
|
|
return unix.IoctlSetPointerInt(fd, unix.TIOCSPGRP, pid)
|
2018-01-17 22:02:47 +00:00
|
|
|
}
|
|
|
|
|
2020-10-03 11:27:23 +00:00
|
|
|
func startForeground(cmd *exec.Cmd) (bg func() error, err error) {
|
2018-01-17 22:02:47 +00:00
|
|
|
// open the TTY, we need the file descriptor
|
|
|
|
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
|
|
|
|
if err != nil {
|
2018-01-26 18:21:14 +00:00
|
|
|
debug.Log("unable to open tty: %v", err)
|
|
|
|
bg = func() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return bg, cmd.Start()
|
2018-01-17 22:02:47 +00:00
|
|
|
}
|
|
|
|
|
2023-05-25 15:31:51 +00:00
|
|
|
signal.Ignore(unix.SIGTTIN)
|
|
|
|
signal.Ignore(unix.SIGTTOU)
|
2018-01-17 22:02:47 +00:00
|
|
|
|
|
|
|
// run the command in its own process group
|
2023-05-25 15:31:51 +00:00
|
|
|
cmd.SysProcAttr = &unix.SysProcAttr{
|
2018-01-17 22:02:47 +00:00
|
|
|
Setpgid: true,
|
|
|
|
}
|
|
|
|
|
|
|
|
// start the process
|
|
|
|
err = cmd.Start()
|
|
|
|
if err != nil {
|
|
|
|
_ = tty.Close()
|
|
|
|
return nil, errors.Wrap(err, "cmd.Start")
|
|
|
|
}
|
|
|
|
|
|
|
|
// move the command's process group into the foreground
|
2023-05-25 15:31:51 +00:00
|
|
|
prev := unix.Getpgrp()
|
2018-01-17 22:02:47 +00:00
|
|
|
err = tcsetpgrp(int(tty.Fd()), cmd.Process.Pid)
|
|
|
|
if err != nil {
|
|
|
|
_ = tty.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
bg = func() error {
|
2023-05-25 15:31:51 +00:00
|
|
|
signal.Reset(unix.SIGTTIN)
|
|
|
|
signal.Reset(unix.SIGTTOU)
|
2018-01-17 22:02:47 +00:00
|
|
|
|
|
|
|
// reset the foreground process group
|
|
|
|
err = tcsetpgrp(int(tty.Fd()), prev)
|
|
|
|
if err != nil {
|
|
|
|
_ = tty.Close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return tty.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return bg, nil
|
|
|
|
}
|