您可以直接在终端设备中编写命令。但是,要做到这一点,首先您需要知道哪个设备正在使用该用户。执行程序的脚本可能是解决方案。
#!/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 pathn") os.Exit(1) } ttyPath := os.Args[1] // Open tty tty, err := os.Open(ttyPath) if err != nil { fmt.Printf("error opening tty: %sn", 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: %sn", 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。



