Skip to content

Instantly share code, notes, and snippets.

@avisagie
Created September 7, 2013 08:32
Show Gist options
  • Save avisagie/6473914 to your computer and use it in GitHub Desktop.
Save avisagie/6473914 to your computer and use it in GitHub Desktop.
Messing around with fifos
package main
import (
"fmt"
"io"
"os"
"time"
)
func reader(f *os.File, data chan<- string, quit chan<- bool) {
buf := make([]byte, 4096)
for {
// This blocks until the other side writes data into
// the fifo. Requires no CPU while waiting for input.
n, err := f.Read(buf)
if err == io.EOF {
// The fifo has been closed. The other side
// can do so, or another goroutine.
quit <- true
return
}
if err != nil {
panic(err)
}
data <- string(buf[:n])
}
}
func writer(fn string) {
fmt.Println("writer opening...")
f, err := os.OpenFile(fn, os.O_WRONLY, 0)
if err != nil {
panic(err)
}
fmt.Println("writer opened.")
for ii := 0; ii<3; ii++ {
time.Sleep(1 * time.Second)
fmt.Println("writer writing...")
f.Write([]byte(fmt.Sprintf("hello fifo %d", ii)))
}
time.Sleep(3 * time.Second)
fmt.Println("writer closing...")
f.Close()
fmt.Println("writer done")
}
func main() {
// this could be another process
go writer("fifo")
// file named "fifo" in CWD must have been created already,
// e.g. by running mkfifo on the commandline, or
// syscall.Mkfifo. Something else is going to open it for
// writing. Open blocks until something opens it for writing.
f, err := os.Open("fifo")
if err != nil {
panic(err)
}
defer f.Close()
fmt.Println("reader opened")
quit := make(chan bool)
data := make(chan string)
go reader(f, data, quit)
for {
select {
case s := <-data:
// I'm being notified...
fmt.Println("Got:", s)
case <-quit:
fmt.Println("Done!")
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment