summaryrefslogtreecommitdiff
path: root/exec_linux.go
blob: 233a8480b28ed96359a7ca753e8ac2db78e80112 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package shell

import (
	"fmt"
	"os"
	"os/exec"
	"syscall"
)

func SudoRaw(c []string) {
	args := []string{"-S"}
	args = append(args, c...)
	cmd := exec.Command("sudo", args...)

	// Assign the current process's standard input, output, and error
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	cmd.Stdin = os.Stdin

	// Ensure the process has a terminal session
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setsid: true, // Start a new session
	}

	err := cmd.Run()
	if err != nil {
		fmt.Println("Command execution failed:", err)
	}
}

func Sudo(c []string) error {
	args := []string{"-S"}
	// args := []string{}
	args = append(args, c...)
	cmd := exec.Command("sudo", args...)

	// Open the terminal device directly to preserve input/output control
	tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
	if err != nil {
		fmt.Println("Failed to open /dev/tty:", err)
		return err
	}
	defer tty.Close()

	// Assign the TTY explicitly
	cmd.Stdin = tty
	cmd.Stdout = tty
	cmd.Stderr = tty

	// Ensure the new process gets its own session
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setsid: true, // Start a new session
	}

	// Run the command
	if err := cmd.Run(); err != nil {
		fmt.Println("Command execution failed:", err)
	}

	fmt.Println("\nProcess finished. TTY restored.")
	return nil
}