-
-
Save jimmy947788/964b972b9a9738a27064df720ad1ee74 to your computer and use it in GitHub Desktop.
named pipe with go - infinite loop of write and read
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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