Skip to content

Instantly share code, notes, and snippets.

@nicewook
Created March 5, 2020 06:30
Show Gist options
  • Save nicewook/6c736ae2fea445d974cc8dd2d11faeca to your computer and use it in GitHub Desktop.
Save nicewook/6c736ae2fea445d974cc8dd2d11faeca to your computer and use it in GitHub Desktop.
named pipe with go - infinite loop of write and read
package main
import (
"bufio"
"fmt"
"log"
"os"
"syscall"
)
var pipeFile = "pipe.log"
func main() {
// 1. make named pipe
os.Remove(pipeFile)
err := syscall.Mkfifo(pipeFile, 0666)
if err != nil {
log.Fatal("Make named pipe file error:", err)
}
fmt.Println("open a named pipe file for read.")
// Writer
go scheduleWrite()
// Reader
file, err := os.OpenFile(pipeFile, os.O_CREATE|os.O_RDONLY, os.ModeNamedPipe)
if err != nil {
log.Fatal("Open named pipe file error:", err)
}
reader := bufio.NewReader(file)
for {
line, err := reader.ReadBytes('\n')
if len(line) == 0 {
continue
}
if err == nil {
fmt.Print("load string:" + string(line))
// fmt.Print(".")
} else {
_ = line
fmt.Printf("READ err: %v\n", err)
}
}
file.Close()
}
// Writer
func scheduleWrite() {
fmt.Println("start schedule writing.")
i := 0
f, err := os.OpenFile(pipeFile, os.O_CREATE|os.O_WRONLY|os.O_SYNC, 0777)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
for {
_, err = f.WriteString(fmt.Sprintf("%d\n", i))
if err != nil {
fmt.Println("WRITE err:", err)
}
_, err = f.WriteString(fmt.Sprintf(" %d\n", i))
if err != nil {
fmt.Println("WRITE err:", err)
}
i++
}
f.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment