Skip to content

Instantly share code, notes, and snippets.

@SCP002
Last active March 15, 2022 22:00
Show Gist options
  • Save SCP002/c7c3bf4aafd3e32e0dc0aa65dda2bf14 to your computer and use it in GitHub Desktop.
Save SCP002/c7c3bf4aafd3e32e0dc0aa65dda2bf14 to your computer and use it in GitHub Desktop.
Golang: Write a message to any console's input on POSIX.
// Used in https://github.com/SCP002/terminator.
// For Windows, see: https://gist.github.com/SCP002/1b7fd91a519a2dc60fc5b179f90472b6.
package main
import (
"fmt"
"os"
"syscall"
"unsafe"
"github.com/shirou/gopsutil/v3/process"
)
func main() {
var pid int
fmt.Print("PID: ")
fmt.Scanln(&pid)
err := Write(pid, "Hello, World!\n")
if err != nil {
panic(err)
}
}
// Write writes a message to the console's input.
//
// Requires root privilegies (e.g. run as sudo).
func Write(pid int, msg string) error {
proc, err := process.NewProcess(int32(pid))
if err != nil {
return err
}
term, err := proc.Terminal()
if err != nil {
return err
}
f, err := os.OpenFile("/dev" + term, os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
for _, c := range msg {
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCSTI, uintptr(unsafe.Pointer(&c)))
if err != 0 {
return err
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment