Skip to content

Instantly share code, notes, and snippets.

@akamensky
Created January 16, 2016 11:23
Show Gist options
  • Save akamensky/48ad7009af2cd9474447 to your computer and use it in GitHub Desktop.
Save akamensky/48ad7009af2cd9474447 to your computer and use it in GitHub Desktop.

This is an example. To run it simply do go build -o slave slave.go && go build -o main main.go && ./main Then you can try typing say for slave process to produce output or exit for slave process to exit. There is an issue when slave exits main process still alive and starts burning through CPU cycles.

But I am lazy to fix that, feel free to do that.

package main
import (
"bufio"
"fmt"
"strings"
"os"
"os/exec"
"io"
"sync"
)
var in chan string = make(chan string, 20)
var out chan string = make(chan string, 20)
var cmd *exec.Cmd
var slaveStdin io.WriteCloser
var slaveStdout io.ReadCloser
func main() {
wg := sync.WaitGroup{}
wg.Add(1)
startSlave()
go localWriter()
go localReader()
go slaveWriter()
go slaveReader()
wg.Wait()
}
func startSlave() {
cmd = exec.Command("./slave")
slaveStdin, _ = cmd.StdinPipe()
slaveStdout, _ = cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
panic(err)
}
}
func localWriter() {
for {
text := strings.TrimSpace(<-out)
if text != "" {
fmt.Println(text)
}
}
}
func localReader() {
input := bufio.NewReader(os.Stdin)
for {
text, err := input.ReadString('\n')
if err != nil {
continue
}
in <- strings.TrimSpace(text)
}
}
func slaveWriter() {
for {
text := strings.TrimSpace(<-in)
if text != "" {
io.WriteString(slaveStdin, text+"\n")
}
}
}
func slaveReader() {
input := bufio.NewReader(slaveStdout)
for {
text, err := input.ReadString('\n')
if err != nil {
continue
}
out <- strings.TrimSpace(text)
}
}
package main
import (
"bufio"
"fmt"
"strings"
"os"
)
var in chan string = make(chan string, 20)
var out chan string = make(chan string, 20)
func main() {
go writer()
go reader()
for {
command := <-in
switch command {
case "exit":
os.Exit(0)
break
case "say":
out<- "Speaking..."
break
}
}
}
func writer() {
for {
text := strings.TrimSpace(<-out)
if text != "" {
fmt.Println(text)
}
}
}
func reader() {
input := bufio.NewReader(os.Stdin)
for {
text, err := input.ReadString('\n')
if err != nil {
continue
}
in <- strings.TrimSpace(text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment