Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fun with Named Pipes
Shell 1 // this will create a named pipe @ /tmp/gfifo and read from the pipe 4eva
> ./gopipe
2014/03/12 20:53:35 Created Pipe
Shell 2
> echo "ASD" > /tmp/gfifo
Shell 1 // prints bytes
> [65 83 68]
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"os/signal"
"log"
)
func main() {
createPipe()
defer cleanUpPipe()
initSigs()
read()
}
// create a named pipe on start up using mknod
func createPipe() {
_ , err := exec.Command("mknod", "/tmp/gfifo", "p").Output()
if err != nil{
panic(err)
}
log.Print("Created Pipe")
}
// clean up the named pipe
func cleanUpPipe() {
err := os.Remove("/tmp/gfifo")
if err != nil{
panic(err)
}
log.Print("Cleaned Up Pipe")
}
func read() {
f, err := os.Open("/tmp/gfifo")
if err != nil{
panic(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
fmt.Println(scanner.Bytes()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
read()
}
// capture os signals
func initSigs() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
go func() {
s := <-c
log.Print("Got signal: ", s)
cleanUpPipe()
os.Exit(1)
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment