Last active
August 29, 2015 13:57
-
-
Save asmedrano/9519922 to your computer and use it in GitHub Desktop.
Fun with Named Pipes
This file contains 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
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] |
This file contains 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" | |
"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