Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@asmedrano
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asmedrano/9519922 to your computer and use it in GitHub Desktop.
Save asmedrano/9519922 to your computer and use it in GitHub Desktop.
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