golang通过named pipes实现IPC通信

golang基于named pipes实现进程间的IPC通信

可以单独使用go write()或 go read()方法

write()是非阻塞的,read()是阻塞的。

package main

import (
	"fmt"
	"log"
	"os"
	"time"
	"bufio"
	"syscall"
)

var pipeFile = "/tmp/pipe.ipc"

func main() {
	os.Remove(pipeFile)
	err := syscall.Mkfifo(pipeFile, 0666)
	if err != nil {
		log.Fatal("create named pipe error:", err)
	}
	go write()
	go read()
	for {
		time.Sleep(time.Second * 1000)
	}
}

func read(){
	fmt.Println("open a named pipe file for read.")
	file, _ := os.OpenFile(pipeFile, os.O_RDWR, os.ModeNamedPipe)
	reader := bufio.NewReader(file)

	for {
		line, err := reader.ReadBytes('\n')
		fmt.Println("read...")
		if err == nil {
			fmt.Print("load string: " + string(line))
		}
	}
}

func write() {
	fmt.Println("start schedule writing.")
	f, err := os.OpenFile(pipeFile, os.O_RDWR, 0777)
	if err != nil {
		log.Fatalf("error opening file: %v", err)
	}
	i := 0
	for {
		fmt.Println("write string to named pipe file.")
		f.WriteString(fmt.Sprintf("test write times:%d\n", i))
		i++
		time.Sleep(time.Second)
		if i == 10{
			break
		}
	}
}

 

第二种

来源:https://gist.github.com/matishsiao/fc1601a3a3f37c70d91ab3b1ed8485c4

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"syscall"
	"time"
)

var pipeFile = "pipe.log"

func main() {
	os.Remove(pipeFile)
	err := syscall.Mkfifo(pipeFile, 0666)
	if err != nil {
		log.Fatal("Make named pipe file error:", err)
	}
	go scheduleWrite()
	fmt.Println("open a named pipe file for read.")
	file, err := os.OpenFile(pipeFile, os.O_CREATE, os.ModeNamedPipe)
	if err != nil {
		log.Fatal("Open named pipe file error:", err)
	}

	reader := bufio.NewReader(file)

	for {
		line, err := reader.ReadBytes('\n')
		if err == nil {
			fmt.Print("load string:" + string(line))
		}
	}
}

func scheduleWrite() {
	fmt.Println("start schedule writing.")
	f, err := os.OpenFile(pipeFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
	if err != nil {
		log.Fatalf("error opening file: %v", err)
	}
	i := 0
	for {
		fmt.Println("write string to named pipe file.")
		f.WriteString(fmt.Sprintf("test write times:%d\n", i))
		i++
		time.Sleep(time.Second)
	}
}


/* Test result */
/*================================
go run pipe.go
open a named pipe file for read.
start schedule writing.
write string to named pipe file.
load string:test write times:0
write string to named pipe file.
load string:test write times:1
write string to named pipe file.
load string:test write times:2
=================================*/

  

posted on 2019-05-07 14:58  WalkerWang731  阅读(5009)  评论(0编辑  收藏  举报

导航