弑天下
您可以直接在终端设备中编写命令。但是,要做到这一点,首先您需要知道用户正在使用哪个设备。执行程序的脚本可以是一种解决方案。#!/bin/bashecho Running from foo script, pid = $$go run foo.go `tty`然后,程序必须将命令写入终端设备。package mainimport ( "C" "fmt" "os" "syscall" "unsafe")func main() { // Get tty path if len(os.Args) < 2 { fmt.Printf("no tty path\n") os.Exit(1) } ttyPath := os.Args[1] // Open tty tty, err := os.Open(ttyPath) if err != nil { fmt.Printf("error opening tty: %s\n", err.Error()) os.Exit(2) } defer tty.Close() // Write a command cmd := "echo Hello from go, pid = $$\n" cmdstr := C.CString(cmd) cmdaddr := uintptr(unsafe.Pointer(cmdstr)) for i := range []byte(cmd) { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, tty.Fd(), syscall.TIOCSTI, cmdaddr+uintptr(i)) if uintptr(err) != 0 { fmt.Printf("syscall error: %s\n", err.Error()) os.Exit(3) } }}这是一个示例输出:$ echo $$70318$ ./foo Running from foo script, pid = 83035echo Hello from go, pid = $$$ echo Hello from go, pid = $$Hello from go, pid = 70318请注意,我正在使用./not执行脚本source,因此脚本的 PID 不同。但是后来,go程序执行的命令有相同的PID。