Skip to content

Instantly share code, notes, and snippets.

@extremecoders-re
Created November 21, 2022 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save extremecoders-re/39aeddda340a613245734218b116dc5f to your computer and use it in GitHub Desktop.
Save extremecoders-re/39aeddda340a613245734218b116dc5f to your computer and use it in GitHub Desktop.
Interactive Process Shell
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"sync/atomic"
"time"
)
var gateOpen uint32
func monitorStdout(pipe io.ReadCloser) {
scanner := bufio.NewScanner(pipe)
for scanner.Scan(){
text := scanner.Text()
if gateOpen == 1 {
fmt.Println(text)
}
}
}
func startRepl(stdin io.WriteCloser, stdout io.ReadCloser) {
scanner := bufio.NewScanner(os.Stdin)
go monitorStdout(stdout)
fmt.Print("# ")
for scanner.Scan(){
cmdtext := scanner.Text()
if cmdtext == "quit" {
stdin.Write([]byte{1, 120})
break
} else {
atomic.StoreUint32(&gateOpen, 1)
time.AfterFunc(1*time.Second, func() {
atomic.StoreUint32(&gateOpen, 0)
fmt.Print("# ")
})
stdin.Write([]byte{10})
stdin.Write([]byte(cmdtext))
stdin.Write([]byte{10})
}
}
}
func run(command string, args []string) {
fmt.Println(command, args)
cmd := exec.Command(command, args...)
stdinPipe, _ := cmd.StdinPipe()
stdoutPipe, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
panic(err)
}
startRepl(stdinPipe, stdoutPipe)
cmd.Process.Kill()
}
func main() {
if len(os.Args) > 1 {
cmdToRun := os.Args[1]
var optionalArgs []string
if len(os.Args) > 2 {
optionalArgs = os.Args[2:]
}
run(cmdToRun, optionalArgs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment