又比如,os.Pipe函数可以创建命名管道,而os/exec代码包则对另一类管道(匿名管道)提供了支持。对于 socket,Go 语言与之相应的程序实体都在其标准库的net代码包中。
Golang实现匿名管道_泡狐的博客-优快云博客_golang stdoutpipe
golang 有名管道通信 总结分析
golang 有名管道通信 总结分析_wjw7869的专栏-优快云博客
/*
* main.cpp
*
* Created on: Jul 16, 2014
* Author: john
*/
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<iostream>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
//#define FIFO_READ "/tmp/writefifo"
#define FIFO_WRITE "/tmp/readfifo"
#define BUF_SIZE 1024
int main()
{
int wfd;
char ubuf[BUF_SIZE]={0};
umask(0);
if(mkfifo(FIFO_WRITE,S_IFIFO|0666))
{
cout<<"sorry the namedpipe created error"<<strerror(errno)<<endl;
exit(0);
}
umask(0);
wfd=open(FIFO_WRITE,O_WRONLY);
if(wfd==-1)
{
cout<<"open named pipe error"<<FIFO_WRITE<<strerror(errno)<<endl;
exit(1);
}
cout<<"begin...\n";
int nCount=0;
while(1)
{
cout<<"please input the content:"<<endl;
cin>>ubuf;
if(strcmp(ubuf,"exit")==0)
{
exit(0);
}
int leng= write(wfd,ubuf,strlen(ubuf));
if(leng>0)
{
cout<<"write..."<<nCount<<endl;
nCount++;
}
}
}
/*
* main.cpp
*
* Created on: Jul 16, 2014
* Author: john
*/
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<iostream>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
#define FIFO_READ "/tmp/readfifo"
#define BUF_SIZE 1024
int main()
{
int rfd;
char ubuf[BUF_SIZE]={0};
umask(0);
while((rfd=open(FIFO_READ,O_RDONLY))==-1)
{
cout<<"open..."<<strerror(errno)<<endl;
sleep(1);
}
cout<<"begin...\n";
int nCount=0;
while(1)
{
int len=read(rfd,ubuf,BUF_SIZE);
if(len>0)
{
ubuf[len]='\0';
cout<<"server:"<<ubuf<<endl;
cout<<"read.."<<nCount<<endl;
nCount++;
}
}
}
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
}
}
}